Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 19 June 2014

Arrays In JavaScript

Arrays

To declare a variable that contains an empty array, you use square brackets with nothing between them:
var a = [];
Console:
typeof a;
Output:
"object"
*typeof returns "object"

To define an array that has three elements, you do this:
var a = [1,2,3];
When you simply type the name of the array in the Firebug console, it prints the contents of the array: 
Console:
Output:
[1, 2, 3]

So what is an array exactly? It's simply a list of values. Instead of using one variable to store one value, you can use one array variable to store any number of values as elements of the array.
The elements contained in an array are indexed with consecutive numbers starting from zero. The first element has index (or position) 0, the second has index 1 and so on.

Here's the three-element array from the previous example: 
Index Value
0 1
1 2
2 3
In order to access an array element, you specify the index of that element inside square brackets. So a[0] gives you the first element of the array a , a[1] gives you the second, and so on. 
Console:
a[0] 
Output:
Console:
a[1] 
Output:
2

Adding/Updating Array Elements

Using the index, you can also update elements of the array. The next example updates the third element (index 2) and prints the contents of the new array. 
Console:
a[2] = 'three'; 
Output:
"three" 
Console:
Output:
[1, 2, "three"] 
You can add more elements, by addressing an index that didn't exist before. 
Console:
a[3] = 'four';
Output:
[1, 2, "three", "four"]

If you add a new element, but leave a gap in the array, those elements in between are
all assigned the undefined value. Check out this example: 
Console:
var a = [1,2,3];
a[6] = 'new';
Output:
[1, 2, 3, undefined, undefined, undefined, "new"] 

Deleting Elements

In order to delete an element, you can use the delete operator. It doesn't actually
remove the element, but sets its value to undefined . After the deletion, the length of
the array does not change. 
Console:
var a = [1, 2, 3];
delete a[1];
Output:
[1, undefined, 3]

Arrays of arrays

An array can contain any type of values, including other arrays. 
Console:
var a = [1, "two", false, null, undefined];
Output:
[1, "two", false, null, undefined] 
Console:
a[5] = [1,2,3]
Output:
[1, "two", false, null, undefined, [1, 2, 3]]

Let's see an example where you have an array of two elements, each of them being an array. 
Console:
var a = [[1,2,3],[4,5,6]];
Output:
[[1, 2, 3], [4, 5, 6]] 
The first element of the array is a[0] and it is an array itself. 
Console:
a[0] 
Output:
[1, 2, 3] 
To access an element in the nested array, you refer to the element index in another set of square brackets. 
Console:
a[0][0] 
Output:
Console:
a[1][2] 
Output:


Note also that you can use the array notation to access individual characters inside a string. 
Console:
var s = 'one';
s[0] 
Output:
"o" 
Console:
s[1] 
Output:
"n" 
Console:
s[2] 
Output:
"e"

Remembering that:

  • An array is a data store
  • An array contains indexed elements
  • Indexes start from zero and increment by one for each element in the array
  • To access array elements we use the index in square brackets
  • An array can contain any type of data, including other arrays

Thursday, 20 March 2014

Function Definition- Three Way to Define a JavaScript Function

There are 3 ways you can define a function.

1. Using Function constructor

var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30

2. Using Function declaration.

function sum(a, b)
{
    return a + b;
}

alert(sum(10, 10)); //Alerts 20;

3. Function Expression

var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10
 
 

Difference between declaration and expression: 

From ECMA Script specification:
FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }
FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
 
var sum = function mySum(a, b) { return a + b; }

Important point to note is that you can use 'mySum' only inside the mySum function body, not outside.

See following example:

var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

Sunday, 9 February 2014

How web pages works - jQuery

How web pages works?

1.   The browser requests a web page from a server when someone types a web address into the browser’s URL bar.
2.    The server finds the requested file(s) and sends them to the browser
3.    The browser displays a rendered HTML page based on the file sent from the server.



The power of script

To change your web pages on the fly, with an HTML tag known as <script>


Role of jQuery (and JavaScript)

Every browser comes with a built-in JavaScript interpreter that takes the directions you write in between the <script>tags and translates those directions into different kinds of action on the web page.
jQuery is a JavaScript library specialized for changing web page documents on the fly.

 

What is jQuery?

What is JavaScript?

JavaScript is a scripting language that was designed for use within a web browser. Typically, JavaScript is used for interface interactions. Slideshows and other interactive components are typically done using JavaScript.

What is jQuery?

jQuery is a lightweight, "write less, do more", JavaScript library.
jQuery is an open source, cross-browser, CSS3 compliant JavaScript library that has made client side scripting relatively easier. It can produce dynamic web pages as well as Flash-like animations. jQuery today powers over 55% of the 10,000 most visited websites on the internet.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
       HTML/DOM manipulation
       CSS manipulation
       HTML event methods
       Effects and animations
       AJAX
       Utilities

 

Why jQuery?

  1. It comes with MIT License (http://opensource.org/licenses/MIT) and is open source.
  2. Cross-browser Compatibility  
  3. Fast & Small Footprint
  4. Short Learning curve & Great Documentation (http://docs.jquery.com)
  5. Tons of Plugins and Helpful Utilities(jQuery UI)
  6. CSS3 Selectors Compliant
  7. Widespread Adoption
  8. Bugs free or fixed pretty quick

Why not jQuery?

       jQuery is easy to accomplish, but not always easy to implement as compared to, say, CSS.
       Even though it is swift, the end product may not always be fast-paced.
       You just have to get the version correct, and pray that you keep getting it correct.
       If improperly used as a framework, things can get complicated beyond measure.

Tuesday, 21 January 2014

Dynamically add button, textbox, input, radio elements in html form using JavaScript

Adding Elements like textbox, button, radio button etc in a html form using JavaScript is very simple. JavaScript’s document object has a method called createElement() which can be used to create html elements dynamically.
We had used this function in our tutorial: Dynamic combobox-listbox-drop-down using javascript to add dynamic options to a combo box-listbox. Let us use this function to create textboxes, radio buttons, buttons etc dynamically and add them in our page.

Following is the source code of our example.
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add(type) {
    //Create an input type dynamically.
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);
    var foo = document.getElementById("fooBar");
    //Append the element in page (in span).
    foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<SELECT name="element">
    <OPTION value="button">Button</OPTION>
    <OPTION value="text">Textbox</OPTION>
    <OPTION value="radio">Radio</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar">&nbsp;</span>
</FORM>
</BODY>
</HTML>
Also note that we have used setAttribute() method to assign the attributes to our dynamically created element. 

Demo: CODE-PEN