I’m just learning JavaScript and it seems like there are a number of ways to declare arrays.
var myArray = new Array()var myArray = new Array(3)var myArray = ["apples", "bananas", "oranges"]var myArray = [3]
What are their difference, and what are the preferred ways?
According to this website the following two lines are very different:
var badArray = new Array(10); // creates an empty Array that's sized for 10 elements
var goodArray= [10]; // creates an Array with 10 as the first element
As you can see these two lines do two very different things. If you
had wanted to add more than one item then badArray would be
initialized correctly since Javascript would then be smart enough to
know that you were initializing the array instead of stating how many
elements you wanted to add.
Is what the authors trying to say is Array(10) creates an array with precisely 10 elements and [10] creates an array of undefined size with the 0th element being 10? Or what does this mean?
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike
Array‘s. What’s more,Arrayis not a keyword, and although it is not a realistic situation, someone could easily overwrite it:However, the larger issue is that of consistency. Someone refactoring code could come across this function:
As it turns out, only
fetchValue(0)is ever needed, so the programmer drops the other elements and breaks the code, because it now returnsundefined: