Few tips on JavaScript – Part I

Properties in double quotes

var myArray=["test","xyz","great"];
console.log("MyArray Length (Without Quotes)="+myArray.length);
console.log("MyArray Length (With Quotes)="+myArray["length"]);

Output
MyArray Length (Without Quotes)=3
MyArray Length (With Quotes)=3

Description
As we know that we can access Array properties by array name with dot notation. But we also can access the array properties through the array square bracket within the quote. The array operator (square brackets) is also used for accessing the array’s properties (arrays are also objects in JavaScript) .So we can access the array length property within the quotes in the array square bracket.

Accessing Array index in double quotes

var myArray=["test","xyz","great"];
console.log("Accessing Array index without quote="+myArray[1]);
console.log("Accessing Array index with quote="+myArray["1"]);

Output
Accessing Array index without quote=xyz
Accessing Array index with quote=xyz

Description
Similarly we can access the array index with the quote inside the square bracket. It’s possible to quote the JavaScript array indexes as well (e.g., myArray[“1”] instead of myArray[1]), although it’s not necessary. The 1 in myArray[1] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that “1” and “01” would refer to two different slots on the myArray object.

Behavior of Boolean value with different datatype

var myArray=[true,"50",5];  
var sum=myArray[0]+myArray[1]+myArray[2]; // i.e. true + "50" + 5
console.log(sum);

Output
true505

Description
Here the true is added with a string value “50” so it is getting concatenated to true50 then it is concatenated to 5. So we got the result as true505.

Now let’s change the position of the array element little bit as follows

myArray=[true+5+"50"];
var sum=myArray[0]+myArray[1]+myArray[2]; // i.e. true + 5 + "50"
console.log(sum);

Output
650

Description
Here the true is added with a number value so the true value is first converted to number which is 1 then it is getting added to 5 and the result will be 6 and then the 6 is getting added to the string value “50” and the final result will be 650

Written By: Debashrita Swain, Software Developer, Mindfire Solutions

Advertisements

2 thoughts on “Few tips on JavaScript – Part I

  1. Pingback: Few tips on JavaScript – Part II | MindfireMobile

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s