06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Data Structures and Manipulation<br />

We discussed briefly that <strong>JavaScript</strong> arrays are not really arrays in a traditional sense.<br />

In <strong>JavaScript</strong>, arrays are objects that have the following characteristics:<br />

• The length property<br />

• The functions that inherit from Array.prototype (we will discuss this in the<br />

next chapter)<br />

• Special handling for keys that are numeric keys<br />

When we write an array index as numbers, they get converted to strings—arr[0]<br />

internally becomes arr["0"]. Due to this, there are a few things that we need to be<br />

aware of when we use <strong>JavaScript</strong> arrays:<br />

• Accessing array elements by an index is not a constant time operation as it is<br />

in, say, C. As arrays are actually key-value maps, the access will depend on<br />

the layout of the map and other factors (collisions and others).<br />

• <strong>JavaScript</strong> arrays are sparse (most of the elements have the default value),<br />

which means that the array can have gaps in it. To understand this, look at<br />

the following snippet:<br />

var testArr=new Array(3);<br />

console.log(testArr);<br />

You will see the output as [undefined, undefined, undefined]—<br />

undefined is the default value stored on the array element.<br />

Consider the following example:<br />

var testArr=[];<br />

testArr[3] = 10;<br />

testArr[10] = 3;<br />

console.log(testArr);<br />

// [undefined, undefined, undefined, 10, undefined, undefined,<br />

undefined, undefined, undefined, undefined, 3]<br />

You can see that there are gaps in this array. Only two elements have elements<br />

and the rest are gaps with the default value. Knowing this helps you in a couple of<br />

things. Using the for...in loop to iterate an array can result in unexpected results.<br />

Consider the following example:<br />

var a = [];<br />

a[5] = 5;<br />

for (var i=0; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!