How Arrays are made
Question:
Describe JavaScript arrays and explain the different ways to construct them.
An array is like a variable in that it can hold any type of data but where its different is that it can hold more than one value at a time.
var name = "oscar"; // just a variable can only hold one value
// array can hold multiple values and different data types
var names = ["oscar","john","bob","Sarah","Kole",3,5]
Each piece of data in an array is called an element and each element has an index value. The table below shows us, using the array we created above to show each element has a corresponding index value.
To write the index value you get the array name followed by the square brackets with the number position of the array in-between them. Index values start at 0 not 1 this is because computers start at zero not 1.
INDEX VALUE | names[0] | names[1] | names[2] |
---|---|---|---|
ELEMENTNAME | "oscar" | "john" | "bob" |
Arrays can store lots of items(2^32 exactly) and you don’t have to specify upfront how many items you need if you don’t know.
How to make an Array
You have already seen the preferred way to make an array. This is called an array literal and is easier to write than the next method I will take about.
// array literal preferred method
var names = [];
// constructor array
var names = new Array();
As you can see the constructor way to make an Array is rather verbose making it likely that you’ll mistype something.
Special Notes
You can also create an empty array and assign values by using each arrays index like you would use a variable like so :
var mySuper = [];
mySuper[0] = "strength";
mySuper[1] = "speed";
mySuper[2] = "invisibility";