Learning JavaScript has led me to discover the various methods for declaring arrays.
var myArray = new Array()
var myArray = new Array(3)
var myArray = ["apples", "bananas", "oranges"]
var myArray = [3]
What sets them apart and which ways are typically preferred?
Upon visiting this website, I found an explanation highlighting the difference between these two lines:
var badArray = new Array(10); // creates an empty Array sized for 10 elements
var goodArray= [10]; // creates an Array with 10 as the first element
These two lines clearly perform distinct actions. When initializing an array with more than one item, badArray is the proper choice as Javascript will understand that you are initializing the array rather than specifying the number of elements to add.
My understanding is that Array(10)
generates an array with exactly 10 elements, while [10]
forms an array with an undefined size where the first element is 10. Can someone confirm this interpretation?