How Weird are JavaScript Arrays?

How weird are JavaScript arrays? Really weird.

In most programming languages that I’ve worked with, arrays and objects are two different types. An array is a pie, and an object is a cake.

JavaScript is so object-oriented that it’s difficult to draw a line between the pie and the cake. In JavaScript, arrays are cheesecake. This can be disturbing, It can make some programmers angry. I’m going to ask you to try to remain calm. If I upset you, please, just walk away.

It all starts out normally (like the first scene of a Hitchcock film). No surprises yet. Let’s look at an object and an array.

var obj={"species":"dog","name":"buster"};
var arr=["dog","buster"];
alert(obj.species); //dog
alert(arr[0]); //dog

Pretty close. The object uses braces, rather than square brackets. While the object labels its elements, the array numbers them. You use dot notation to get at the info in an object, and the square brackets (array notation) to get at the info in an array.

Now it Starts to Get Interesting

We can also get at object values with this array-like syntax:

alert(obj["species"]); //dog

Now, our object looks almost like an array.

In most languages, arrays are optimized for speed. Each element is the same type and size and can be quickly accessed. In JavaScript, arrays are so loose that there’s really no speeding them up. Each array element can hold a different type.

arr[0]='pig';
arr[1]=true;
arr[2]=[5,2,7,3];
arr[3]={'a':1,'b':2};

An array element can even hold a function (or an array of functions)!

This is massively handy, if unusual.

Sit Down, I Have Something Scary to Tell You

I’m sorry, but it’s time for me to do something that may weird you out. Look at this…

arr["state"]=0;

That’s upsetting. Arrays can do more than just hold their numbered elements, they can also act just like objects, holding named values. If you want to kick something, or yell, I don’t blame you. If you need to take a few deep breaths, I understand.

You have a choice to make. You need to get all cold, steely, and rational and decide if it makes sense to take advantage of what JavaScript offers, or if you’re better off backing off and doing things the way you’d do them in other languages. That depends on your situation. Are you the only coder who will ever see the code? If you’re working with others, you may very well blow their minds if you treat an array like an object. Or maybe you’re working with some like-minded cheesecake aficionados.

Are You Insane?

But there are some very nice things you can do with this. Having all information that’s associated with the array (maybe even the array’s methods) live inside the array can make your code easier to deal with and understand, but only if you understand that an array is a cheesecake.

If you don’t take advantage of this, but you do want to keep everything associated with the array together, you’ll use an object to wrap everything up, and the array will be part of the object. This is more clear to the traditional thinker, but it does have a cost–the overhead of all the extra symbols you’ll be typing to access things.

Here are an array and an object, both designed to hold the same things.

var arr=[],obj={};
arr.state=0;
arr[0]='dog';
arr[1]='cat';
obj.state=0;
obj.data=[];
obj.data[0]='dog';
obj.data[1]='cat';

I can make a pretty good case that the array is “better” in this case, assuming you’re a big fan of cheesecake.

---

True Story.

I once took a cat into the vet. It was my first time there so I had to fill out a form. One of the things they wanted to know was the pet's species.

Crap. I dug deep into the part of my brain that was supposed to be holding on to my high school Latin, but I just couldn't quite get it. I made a stab--felis domesticatus--no, can't be right.

I walked up to the lady at the desk.

"Do people really know this?"

"Know what?"

"The species of their pet."

"Yeah, usually."

I pointed at my cat. "What's this?"

She blinked, then answered, "It's a cat."

About these ads

6 Comments

  1. August 2, 2008 at 4:56 pm

    [...] Functions are Weird, Too Remember when I talked about JavaScript arrays being weird because they are also objects? Aside from their numbered elements, they can have, in addition, objects that are hashes (a key and [...]

  2. bibby said,

    March 5, 2009 at 12:19 am

    Also disturbing-ish about arrays in Javascript is their acceptance of the various “falsey” types as valid keys. This points out that all things extend Object, and thus can have their methods and members accessible using the “associative” array syntax, such as

    typeof []['join'] == ‘function’

    In particular, I present these examples:

    var A=[];
    A[0]=0;
    A[1]=1;
    A[true]=”truthy”;
    A[false]=”falsey”;
    A[null]=”nully”;
    A[undefined]=”undefiney”;
    A[NaN]=”notanumerbery”;

    console.log( A.join(‘, ‘) );
    // 0, 1

    console.log( A[!!1], A[!1], A[null], A[undefined], A[parseInt(":P")] );
    // truthy falsey nully undefiney notanumerbery

    • Nosredna said,

      March 5, 2009 at 12:51 am

      Haha! Great stuff!

    • Xavi said,

      March 26, 2010 at 6:30 pm

      Haha, that is good stuff.

      The key thing to know about A[] is that under the hood, the JS engine calls .toString on before retrieving the index from the array/object. As a result you can do craziness like this:

      var foo = { toString: function() { return “hello”; } };
      var hi = { hello: “hola” };

      hi[foo]; // returns “hola”

    • Xavi said,

      March 26, 2010 at 6:32 pm

      Haha, that is good stuff.

      The key thing to know about A[op] is that under the hood, the JS engine calls .toString on op before retrieving the index from the array/object. As a result you can do craziness like this:

      var foo = { toString: function() { return “hello”; } };
      var hi = { hello: “hola” };

      hi[foo]; // returns “hola”

      Sorry for the spam, key characters were stripped out of my last post… =(

  3. dzek said,

    June 1, 2011 at 8:50 am

    I love the story @ the end of this post :D


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: