What's the real difference between declaring an array like this:
var myArray = new Array();
and
var myArray = [];
[] 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.
{} 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With