Arrays are like lists. Well, they are lists that are called arrays. And you create them like this:
var groceries = ['cheese', 'milk', 'eggs'];
So now we have an array that is stored in memory and you can reach via the reference we have in our variable,
groceries. The square brackets (
) are similar to the curly braces we used earlier to declare our objects. This time, they are used to declare a literal array object.
So now if you typed the following into your Console:
You are going to most likely expect to get the string "array" in return. But go ahead, hit Enter. What did you get? "object"? What?!
The reason the type of our array is "object" is because in JS's case arrays are still objects. They are special objects with special attributes, but their type is still an object. In fact, every data structure in JS that is not one of the five primitives we mentioned earlier is an object!
Arrays have special properties -- they are so special that they are just numbers. If you type the following:
The expression will yield the first element in our array, which is the string "cheese". FYI, in most programming languages the first number is zero (and not one). Zero is a perfectly good number and we should treat it as such. Based on that, the first element in our array is located at the zeroth index. This means that in order for us to get our last grocery (eggs), we'll need to refer to it as this:
groceries; // 'eggs' is at index 2 and NOT 3
Now, remember the
length property that was available in our string example? Well if you don't, it was simply a built in property that had the number of characters in the string. The
length property is also available in arrays and it contains the number of elements in the array. With this knowledge you can do the following:
groceries[groceries.length - 1];
and get the last element in the array even if you didn't know how many elements it contained. Why the subtraction of 1 from the groceries length, you ask? Like we've said, arrays are zero based and so the first element of it is accessed via the index 0. Therefore the length itself, being a simple count of the elements, is 3, but the last element of our array is only at index 2. That's why.
So what are arrays good for if they behave so similarly to regular objects? Well they're good for ordered lists. Whenever you want to store data in a consecutive order and access it as such, use an array! We are going to integrate an array in our application in just a bit so hang tight.