The following text is an excerpt from Kyle Simpson’s “You don’t know JS” and is intended here for SEO experiments only.
function, and regular-expression values, it’s almost universally preferred that you use the literal form for creating the values, but the literal form creates the same sort of object as the constructor form does (that is, there is no nonwrapped value).
Just as we’ve seen above with the other natives, these constructor forms should generally be avoided, unless you really know you need them, mostly because they introduce exceptions and gotchas that you probably don’t really want to deal with.
Array(..) constructor does not require the
new keyword in front of it. If you omit it, it will behave as if you have used it anyway. So
Array(1,2,3) is the same outcome as
Array constructor has a special form where if only one
number argument is passed, instead of providing that value as contents of the array, it’s taken as a length to “presize the array” (well, sorta).
This is a terrible idea. Firstly, you can trip over that form accidentally, as it’s easy to forget.
But more importantly, there’s no such thing as actually presizing the array. Instead, what you’re creating is an otherwise empty array, but setting the
length property of the array to the numeric value specified.
An array that has no explicit values in its slots, but has a
length property that implies the slots exist, is a weird exotic type of data structure in JS with some very strange and confusing behavior. The capability to create such a value comes purely from old, deprecated, historical functionalities (“array-like objects” like the
Note: An array with at least one “empty slot” in it is often called a “sparse array.”
It doesn’t help matters that this is yet another example where browser developer consoles vary on how they represent such an object, which breeds more confusion.