Is
var myCars=new Array("Saab","Volvo","BMW");
and
var myCars=["Saab","Volvo","BMW"];
exactly the same ?
Is
var myCars=new Array("Saab","Volvo","BMW");
and
var myCars=["Saab","Volvo","BMW"];
exactly the same ?
Yep. Well I had to add this sentence to make the answer long enough :)
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.
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);
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 = []
.
check this link
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?