16

Is

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

and

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

exactly the same ?

1

3 Answers 3

34

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);
Sign up to request clarification or add additional context in comments.

7 Comments

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: Yes, you are right. Arrays in Javascript are a bit special in that way... I adjusted the answer.
@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]);
@Daniel, yeah, I think this is one of those myths that are out there all over the place hehe
whats the use of creating and array of length 42 if its empty ?
|
5

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 = [].

Comments

3

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.

Note that there is one behavioural difference: if you pass a single, numeric argument to new Array, like new Array(20), it will return a new array pre-initialised with that number of elements from 0 to n - 1, set to undefined.

1 Comment

and how is that usefull at all ? am refering to your 2nd paragraph

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.