Javascript Arrays

Something really funky about arrays. Find out here.

Arrays are objects. Maybe you already heard that, but have you tested that premise? If they are objects, then they should be able to store any types of data like objects.

var arr = [];
arr.hello = "world"
console.log(arr.hello); //what will this be?

We get the value “world” returned. So it does have some characteristics like objects, but if it’s exactly like a literal object, then why even have arrays? Well, that’s because it has other characteristics that only pertain to arrays. We normally think of arrays as lists. That is, a list of values and not key/pairs like objects. We also think of arrays as being ordered by numbers with 0-index while objects are like hashes(in some programming languages) where the items don’t have any order. So with arrays we can do sort and filter through data through indexes. So let’s take the above example and get the value from the array through an index.

console.log(arr[0]);

You should have gotten undefined because there is nothing defined at index 0. But didn’t we just add an item to the array? Yes, it wasn’t an indexed value, it was a property(key/pair value). Huh? That’s dumb you say. And quite frankly, it is. That is why we have literal objects and array objects.

Array indexes are strings

The bracket operator for objects evaluates an expression and coerces that expression to a string.

var obj = {};
obj.hello = "world";
var hello = "hello";
console.log(obj[hello]); //outputs "world"

Let’s see this in arrays using our array example.

arr.push("bye");
console.log(arr); //outputs ["bye", hello: "world"]
console.log(arr[0]); //outputs bye

So at index “number” 0 is the string “bye”. Let’s add a string “2” property with a value:

arr["2"] = "foo";
console.log(arr); //outputs ["bye", 2: "foo", hello: "world"]

So at index 0 we have a string “bye”. But what’s at index 1?

console.log(arr[1]); //outputs undefined

So at index 2 we should get undefined right?

console.log(arr[2]); //ouputs foo

What?! This makes sense once you understand that indexes are strings. Now look what happens to our property (2: “foo”) once we give something to index 1:

arr[1] = "bar";
console.log(arr); //outputs ["bye", "bar", "foo", hello: "world"]

(2: “foo”) become “foo”. And there’s still nothing at index 3. Let’s further verify that indexes are strings by seeing what’s at string “0”:

console.log(arr["0"]);

Closing Thoughts

So if this all seemed confusing it should be. Arrays are objects but we don’t want to use them as such. We want to use them how we typically are taught to use them. Like lists. If you try and combine the two traditional ideas of objects and arrays like we did in the above examples we get into lots of confusion and trouble. This is also why we have loops that can be used by both, but are better used for their designed purposes. Yes it’s true that functions are objects, but for clarity I’m going to think of arrays as arrays.