Javascript Treachery

Every single time I deal with this, it punches me in the face. I love it because its cool, I hate it because I always forget.

In Javascript, (as well as other Object-Oriented languages) objects (what we used to call “variables” back in the day) can use functions as properties. For instance, in order to access the length of an array in Java, you would access its public method (or function) size().

ArrayList myArray = new ArrayList();
myArray.add("Mutemath is coming back to KC this fall!");
out.write(myArray.size()); // size() = 1

Note the parentheses that follow the size() method: This implies that it is really a function and not a simple property of the object. Most properties of Java objects are private, which are then accessed through public functions, such as get and set methods.

So here I go in Javascript, hacking away at something for 40 minutes trying to return the size of array. I recall that in js it is length() and not size() as is the syntax for its java counterpart.

var l = myArray.length();
alert(l + "!"); // Fiesta. We are really excited about the length of the array.

Alas, length is a property, and not a function. It is accessed only without the parentheses, as no function exists by that name.

var l = myArray.length;

This has happened to me more times than I care to admit.

3 Replies to “Javascript Treachery”

  1. If I had a nickel for every time this happened to me, I’d be broke. But I’d have a lot of nickels. Its things like this that make me thankful that Jesus invented auto-complete for programming IDEs. Otherwise I’d spend more time at work digging through 240,000 pages of uncommented source code looking for object definitions.

  2. If only my Java IDE had completion insight for javascript… alas, it does not.
    Unless I push the javascript into it’s own external file, it doesn’t even do code highlighting right. Seriously.
    You should get a gravatar.

  3. Well I tried signing up for a gravatar, but got this nice little error message:

    “Change this error message for exceptions thrown outside of an action (like in Dispatcher setups or broken Ruby code) in public/500.html”

    Kind of like the error message I got a few days ago at work from IBM:
    “If you are a resident of Italy, your password may have expired. Please back up and try again.”

    Good thing I’m an American where apparently passwords don’t expire.

Leave a Reply

Your email address will not be published. Required fields are marked *