Sunday 3 February 2013


What’s the difference between “Array()” and “[]” while declaring a JavaScript array:

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using
var a = [];


You're telling the interpreter to create a new runtime array. No extra processing necessaryat all. Done.

If you use:
var a = new Array ();


You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.
You may think "Well, this doesn't matter at all.They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array () { 
this . is = 'SPARTA' ; 
} 
var a = new Array (); 
var b = []; 
alert ( a . is ); 
// 'SPARTA' 
alert ( b . is ); 
// undefined 
a . push ( 'Woa' );
// TypeError: a.push is not a function 
b . push ( 'Woa' ); 
// 1 (OK)

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not.You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as 'push', where the other does not.
While you may expect this to happen, it just illustrates the fact that '[]' is not the same as 'new Array()'.

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

No comments:

Post a Comment