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?
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.
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.
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.
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