00 Votes

JavaScript: Should I use new Array()?

Question by Guest | 2015-08-02 at 13:24

As far as I know, there are two different ways you can use to declare an array in JavaScript.

var arr = [1, 2, 3];

// or

var arr = new Array(1, 2, 3);

The first method is just defining the array elements within square brackets while the second method is using the constructor new Array().

Apparently, both ways are delivering exactly the same result. Now, I am uncertain, which method I should better use. Are there any advantages or disadvantages for the one or the other method?

ReplyPositiveNegative
0Best Answer0 Votes

Whenever you want to declare an array with predefined elements, I recommend using the first method and to define the elements of the array within square brackets.

Of course, one advantage is that you do not have to write that much and that the code becomes more clear. But there are also other arguments, not to use new Array() in this case. Let us have a look at the following sample:

var arr = new Array(10);

What does this code do? Is it creating an array containing the element 10? No. Here, we are creating an empty array with 10 elements. Although new Array(10, 11) is creating an array containing the two elements 10 and 11, new Array(10) is creating an empty array containing 10 undefined elements. If we had written "arr = [10]", this would not have happened.

With this, we are at the point at which new Array() makes sense: Every time, we would like to create a new empty array of a specified length, we can use new Array() without any problems. For example, if we want to fill the array later in our code or if we cannot define all elements at the same point.

In summary, I recommend to use the writing with square brackets every time you are using predefined arrays and to use new Array() only if you need an array with out predefined elements and you would like to fill the array later.
2015-08-03 at 18:34

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.