I just started thinking about this, but couldn't get any differences to expose themselves whilst mucking around in jsFiddle.
var a = new Array(1), b = Array(1); console.log(a, b);
Output is two arrays with one undefined member.
Doing a for ( in )
reveals they have the same properties.
What are the differences between these? Does the first one simply instantiate the object explicitly?
Please don't lecture me about using array literal notation as I already know about that. I'm more wishing to fill this gap in my knowledge explained above.
When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
new Array() There are no differences between calling Array() as a function or as a constructor. According to the spec, using Array(…) as a function is equivalent to using the expression new Array(…) to create an Array object instance with the same arguments.
JavaScript Arrays - How to Create an Array in JavaScript. An array is a type of data structure where you can store an ordered list of elements. In this article, I will show you 3 ways you can create an array using JavaScript. I will also show you how to create an array from a string using the split() method.
As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).
With Array
, both are equivalent. The new
is injected when it's called as a function:
15.4.1 The
Array
Constructor Called as a FunctionWhen
Array
is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function callArray(…)
is equivalent to the object creation expressionnew Array(…)
with the same arguments.
From ECMA-262, 3th Edition (with similar in 5th Edition). See also 22.1.1 The Array Constructor in ECMA-262 ECMAScript 2020 specification (11th Edition).
According to Javascript: The Definitive Guide (5th Edition), page 602, "When the Array()
constructor is called as a function, without the new
operator, it behaves exactly as it does when called with the new
operator."
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