views:

83

answers:

5

Is

var myCars=new Array("Saab","Volvo","BMW");

and

var myCars=["Saab","Volvo","BMW"];

exactly the same ?

+3  A: 

Yep. Well I had to add this sentence to make the answer long enough :)

http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Strelok
+1  A: 

Yes, they are the same. There is no primitive form of an Array, as arrays in JavaScript are always objects. The first notation (new Array constructor syntax) was used heavily in the early days of JavaScript where the latter, short notation was not supported well.

Delan Azabani
+8  A: 

Yes, for that case they are the same.

There is a difference if you have only one item, and it's numeric. This will create an array with a single item:

var myNumbers = [42];

but this will create an array with the length 42:

var myNumbers = new Array(42);
Guffa
+1. Nice :) ...
Artem Barger
The second example will not really have `42` items, only its `length` will be `42`. The properties from `0` to `41` don't exist in the object, e.g.: `new Array(42).hasOwnProperty('0'); // false`.
CMS
@CMS: Yes, you are right. Arrays in Javascript are a bit special in that way... I adjusted the answer.
Guffa
@Guffa, another thing, the new third example is not right, both, the literal notation and the use of the `Array` constructor will generate an array with *one* element, that is the inner `[1,2,3]` array, e.g. `new Array([1,2,3]).length == 1`. The behavior described is only possible through something like `Array.apply(null, [1,2,3]);`
CMS
@CMS: It looks like the [Mozilla Dev Center got this one wrong](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Specifying_a_single_parameter) as well: `... The following code creates an array of five elements: var billingMethod = new Array(5);`
Daniel Vassallo
@Daniel, yeah, I think this is one of those *myths* that are out there all over the place hehe
CMS
@CMS: Yes, you are right. I was looking at Microsoft's documentation, but the constructor that handles an array differently only exists in some implementations of Jscript.
Guffa
+2  A: 

Yes, they are. However be aware that when you pass just a single numeric parameter to the Array constructor, you will be specifying the initial length of the array, instead of the value of the first item. Therefore:

var myCars1 = new Array(10);

... will behave differently from the following array literal:

var myCars2 = [10];

... note the following:

console.log(myCars1[0]);          // returns undefined
console.log(myCars1.length);      // returns 10
console.log(myCars2[0]);          // returns 10
console.log(myCars2.length);      // returns 1

That is one reason why it is often recommended to stick to the array literal notation: var x = [].

Daniel Vassallo