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

what'd
what does
how to pronounce what
what w
what's
what is love
whats the meaning of
what c

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

var myArray = new Array();

and

var myArray = [];

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.

What, I will do what I can to help you. TranslationsEdit. show ▽what? (interrogative pronoun)  Quickly send and receive WhatsApp messages right from your computer.

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array() {
    this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);  // => 'SPARTA'
alert(b.is);  // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.

While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

Drake - Nice For What, what definition: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more. noun the true nature or identity of something, or the sum of its characteristics: a lecture on the whats and hows of crop rotation.

There is an important difference that no answer has mentioned yet.

From this:

new Array(2).length           // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true

You might think the new Array(2) is equivalent to [undefined, undefined], but it's NOT!

Let's try with map():

[undefined, undefined].map(e => 1)  // [1, 1]
new Array(2).map(e => 1)            // "(2) [undefined × 2]" in Chrome

See? The semantics are totally different! So why is that?

According to ES6 Spec 22.1.1.2, the job of Array(len) is just creating a new array whose property length is set to the argument len and that's it, meaning there isn't any real element inside this newly created array.

Function map(), according to spec 22.1.3.15 would firstly check HasProperty then call the callback, but it turns out that:

new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true

And that's why you can not expect any iterating functions working as usual on arrays created from new Array(len).

BTW, Safari and Firefox have a much better "printing" to this situation:

// Safari
new Array(2)             // [](2)
new Array(2).map(e => 1) // [](2) 
[undefined, undefined]   // [undefined, undefined] (2) 

// Firefox
new Array(2)             // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined]   // Array [ undefined, undefined ]

I have already submitted an issue to Chromium and ask them to fix this confusing printing: https://bugs.chromium.org/p/chromium/issues/detail?id=732021

UPDATE: It's already fixed. Chrome now printed as:

new Array(2)             // (2) [empty × 2]

what, Usage Note: When what is the subject of a clause, it takes a singular verb if the word or phrase that completes the sentence (the complement) is singular, as in I​  what definition: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more.

Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.

More accurately: Array( is a fast constant time operation that allocates no memory, wheras [] is a linear time operation that sets type and value.

WHAT, what definition: The definition of what is which one or as many as. (adjective) An example of what used as an adjective is in the sentence, "What shirt do you  whatever: adverb at all , of any description , of any kind or sort , whatsoever , whichever

For more information, the following page describes why you never need to use new Array()

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).

What, That's what Zoom did - video calls are nothing new, but Zoom solved a lot of the small pieces of friction that made it fiddly to get into a call. The  WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.

What dictionary definition, Up your lunch sandwich game, with some no-recipe recipe prompts, and make Yotam Ottolenghi's latest — a potato cake, two ways — for  What Is My IP? WhatIsMyIP.com® is the industry leader in providing REAL IP address information. We provide IP address tools that allow users to perform an Internet Speed Test, IP address lookup, proxy detection, IP Whois Lookup, and more.

What comes after Zoom?, What Parents Can Learn From Child Care Centers That Stayed Open During Lockdowns. Facebook; Twitter; Flipboard; Email. Ask.com is the #1 question answering service that delivers the best answers from the web and real people - all in one place.

What to Cook Right Now, Seen a font in use and want to know what it is? Upload an image to WhatTheFont to find the closest matches in our database.

Comments
  • [] token: ARRAY_INIT; new Array tokens: NEW, IDENTIFIER; new Array() tokens: NEW, IDENTIFIER, CALL
  • This is slightly wrong. There is one very important difference between new Array() and [] I'll elaborate in my answer.
  • But as noted in your answer, it's only different if you are completely insane and overwrite the Array function..?
  • Well the importance is that using the new operator causes the interpreter to take all sorts of extra steps to go to the global scope, look for the constructor, call the constructor and assign the result... which in the majority case is going to be a a runtime array. You can avoid the overhead of looking for the global constructor by just using []. It may seem small, but when you're shooting for near real-time performance in your app, it can make a difference.
  • There is a huge performance difference: jsperf.com/create-an-array-of-initial-size/2
  • True, but you also don't need semicolons or line-breaks in most places where I add them. It's about consistency and legibility. You know, IMHO.
  • Well, good to know I suppose. What sort of person would overwrite the array class, I do not know...
  • You're absolutely right. Only a madman would overwrite the array class. Now take a moment and consider all the extra work using new Array() makes the interpreter do to support these madmen. I just avoid it all together with [].
  • Good example of the kind of global pollution that is possible with JavaScript.
  • Worth noting that the new Array(size) is faster than other possible methods using the [] notation. Source: jsperf.com/create-an-array-of-initial-size/2
  • Unfortunately that test is improperly prepared. It's testing an initialization of an Array with initializations of arrays followed by Array access. There's no control to prove that the browsers are actually pre-allocating the memory (which the specification does not say they must do). If we can assume that array access is constant and the majority of the time will be spent allocating memory in both examples then [] could be preferable if you're instantiating millions of arrays. jsperf.com/array-instanciation
  • Yours is the only actual answer