Arrays are a special kind of object. They can store multiple values. Let’s say you had a list of 800 names. If you had to create a variable for each of these names, then that would take a long time. Also, what if you were expecting to update this list with more or remove names? You’d have to manually create more variables or end up with a bunch of empty ones. To solve this dilemma, you can use arrays.
First, let’s learn how to create an array. Update the body tags in your HTML document to this.
Now, let’s learn how to create an array. Clear your script and add this line of code.
var names = new Array( "Jack", "Dan", 35.54, "James" );
You now have a list of values stored under 1 variable. How do you access a certain value? Simple, you use square bracket notation.
Add this line of code after your array.
document.write( names );
In this example, we output the value represented by 2. You should see 35.54 outputted onto the screen.
Let’s say we wanted to add a new value into the array. This is very easy to do. You simply specify the number followed by the value, like so.
names = 'Jesse';
Arrays have a couple of properties that you can use, but only one is really used a lot. That is the length. The length simply returns how many items are in the array. However, you should note that it starts at 1 and counts up. So, if there’s 3 items in the array, then it’ll return 3. Let’s see how this can be useful. Update the line that adds a new item in the array to this.
names[ names.length ] = 'Jesse';
Inside the square brackets is where the magic happens. You don’t necessarily have to type a number literally, but the value inputted into these brackets must be a number. Since the length returns a number, it’ll work. So, why would this be useful instead of hard coding a number?
Since the length literally counts how many items are in the array, then it’ll always return a number that is undefined in the array. For example, our array has 4 items. Each item has a number assigned to it starting from 0. The last item in the array is assigned the number 3. Since, the length returns 4, it’s a sure thing you’ll always add a value and not overwrite any values.
Arrays are useful when working with large amounts of data. If you would like more information about arrays, then go here.