I can hear you now. “You keep telling us that an array is not an Object! What’s up with that post title???”
Apparently there are some people debating on when to use and array vs. when to use an object, MDN notes, and includes several links. We’re not going to worry about that here, since we’re just trying to understand what the Global Array Object even is and what we can do with it.
We’re going to go out of order from MDN’s article, because they list a bunch of things to do with an array before actually defining it. So I’m going to start with the syntax:
element followed by a number – This is whatever you want to populate your array with. You can have as many as you need, although if you create it this way with just one element that is a number, you’ll get an array that is that length rather than an array with that number as an element – it sees it as you doing the third line above. You can circumvent this by doing it the way it’s done on the first line. Don’t worry, there will be examples of all of these below.
arrayLength – this is how long you want the new array to be. It can be any integer between 0 and 2exp32 – 1. That’s a huge range, but if you put a number above or below it, you are going to get a RangeError.
Enough description already! Let’s look at some examples…
First, let’s create an array, with two elements, and then check its length:
Now, just for fun, we’re going to try to access an array element like we would if it was an Object:
console.log(arr.0); // a syntax error
Nope, doesn’t work. That should be console.log(arr);. Let’s get the first element (element[0}) and assign it to a variable:
var first = fruits;// Apple
Mind you, this is the same any time you have a property that starts with digit – it cannot be referenced with “dot notation”. MDN gives an example to demonstrate this, where 3d is the property:
console.log(years[‘2′] != years[’02’]);
Now let’s get a little fancy. Let’s get the last variable by subtracting 1 from the length. We might use this, for example, when we don’t know what the length is.
var last = fruits[fruits.length – 1];// Banana
That’s enough for today. We’ll look at some array methods in a future post!