Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

What's the real difference between declaring an array like this:

var myArray = new Array(); 

and

var myArray = []; 
like image 520
Amr Elgarhy Avatar asked May 31 '09 11:05

Amr Elgarhy


People also ask

Whats the difference between {} and [] in array?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What is the difference between {} and [] in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

What does [] in JavaScript mean?

This answer is not useful. Show activity on this post. It means an array. var openTollDebug = []; declares the openTollDebug variable and initializes it to an empty array.

What is the correct way to declare an array in JavaScript?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


1 Answers

There is a difference, but there is no difference in that example.

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

x = new Array(5); alert(x.length); // 5 

To illustrate the different ways to create an array:

var a = [],            // these are the same     b = new Array(),   // a and b are arrays with length 0      c = ['foo', 'bar'],           // these are the same     d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings      // these are different:     e = [3]             // e.length == 1, e[0] == 3     f = new Array(3),   // f.length == 3, f[0] == undefined  ; 

Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.

As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items. Be aware that using Array this way makes it difficult to rely on array.length for calculations.

like image 112
nickf Avatar answered Oct 17 '22 08:10

nickf