Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using "new" to create a Javascript array considered bad? [duplicate]

W3 Schools says

These two different statements both create a new array containing 6 numbers:

 var points = new Array(40, 100, 1, 5, 25, 10)  // Bad 
 var points =[40, 100, 1, 5, 25, 10];          // Good

but doesn't give an explanation why the first is bad.

From what I understand, the only difference is that the first calls the constructor. Can someone clue me into why the first is bad?

like image 931
Steve Jobs Avatar asked Mar 25 '15 15:03

Steve Jobs


People also ask

What is new array in JavaScript?

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.

How do you create an array with the same value?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.


1 Answers

The true reason is that this constructor is inconsistent.

var points = new Array(40)

creates an array of size 40 and no content while

var points = new Array(40, 50)

creates an array of size 2 with 2 elements.

It's just simpler and more readable to use

var points = [40];

or

var points = [40, 50];

There's also no reason to use this constructor when you want to build a array, just use a literal array, exactly like you're using literal numbers.

Only use the Array constructor when you want to build an empty array with a given size (which should be very rare).

ES 2015 edit:

Due to this inconsistency, ES2015 brought us a new static function, Array.of. Array.of(40) makes the [40] array.

like image 122
Denys Séguret Avatar answered Sep 19 '22 15:09

Denys Séguret