paul bennett

Javascript: testing whether elements or properties exist – the redux

Posted on: February 8, 2007

In my previous post, I detailed how typeof could be used to test if something is present or not. Given that this sounds loosely defined at best, consider the following:


window.onload = function() {
var myObject = new Object();
var myImg = new Image();
var myArray = new Array();
var myString = new String();
theDiv = document.getElementById('n');
theDiv.innerHTML = typeof(myObject) + '<br />' + typeof(myImg) + '<br />' + typeof(myArray) + '<br />' + typeof(myString);
}

What would we expect our div with the id of ‘n’ to contain once the page loads?

I expected sopmething like this:

Object
Image
Array
String

Instead, JavaScript gives you this:

Object
Object
Object
Object

????? Well, in JavaScript, it appears everything is an object. This is no big deal, as typeof still lets you test whether things exist or not.

Now consider this script:

window.onload = function() {
var myObject = new Object();
theDiv = document.getElementById('n');
theDiv.innerHTML = typeof(myObject) + '<br />' + typeof(myUndefinedVariable) + '<br />' + typeof(myObject[0]) + '<br />' + typeof(myObject.myUndefinedProperty)
+ '<br />' + typeof(myObject[0].myUndefinedProperty) ;
}

Our div with the id of ‘n’ would now display:

Object
undefined
undefined
undefined

Right? Right? Right?…. Wrong – Our script will terminate (produce an error) the moment we try to access an undefined object property in an unset array key. So, when we try to call typeof on myObject.myUndefinedProperty things are ok, but when we try to call typeof on myObject[0].myUndefinedProperty, the script dies.

Why? I’m not sure….it just does.

Firefox (we won’t mention IE’s unhelpful JS debugging) gives the error ‘myObject[0] has no properties’ which is absolutely correct, but the property myObject.myUndefinedProperty didn’t exist at all and typeof didn’t fail, so what’s the difference?

The difference:

As explained by someone more knowledgable then I:

Firstly, typeof is not a function, it’s an operator so it’s just
“typeof myObject[0]” – but this is not the reason you can’t do what
you’re trying.

When the code is evaluated, the dot operator takes precedence, it
cannot evaluate the property of an object that does not exist
therefore does not get the chance to perform the typeof.

For the same reason, you couldn’t then go ahead and do:
myObject[0].myUndefinedProperty = foo;.

You’d have to do a myObject[0] = new Object() first. You could use
the object literal: myObject[0] = {myUndefinedProperty:foo;};

So:
if(myObject[0])
alert(typeof myObject[0].myUndefinedProperty);

——————

Want to improve your JavaScript skills? I recommend the following:

About these ads

7 Responses to "Javascript: testing whether elements or properties exist – the redux"

Er, no. You really shouldn’t announce guesses as facts. In ECMAscript, POD types are not objects – integers, floating point values, null and so on. Arrays and strings are objects. Everything else inherits from the Object class.

It’s important to know what is and what isn’t an object, because they have different copy semantics, different argument passing semantics, different reference semantics and so on.

All of these characteristics are defined in ECMAscript, and are true in all correct dialects – JavaScript, JScript, ActionScript and so on.

Time to read the standard.

“…it appears everything is an object.”

For someone who tells others to read, its time you did some. Appearances are deceiving, and the author used the correct language here. He is not stating fact, just what he has interpreted.

>> Edited by me as the last part was a bit inflammatory…

very interesting.
i’m adding in RSS Reader

The fact that there is divergent opinion on this post only serves to reinforce why the original issue was so confusing.

Still, it has helped me understand the way typeof works / doesn’t work, so thanks for chiming in.

I suggest you go through Douglas Crockford’s presentations on Javascript, you’ll get to know a lot more quirky things about Javascript :)

@Jaffer – I’ve been eyeing those in my feed reader for a while. May have to invest some time and hope the IT dept. here doesn’t jump on me for bandwidth use :)

@Paul – trust me, they’re well worth the investment. You get to know the in’s and out’s of Javascript, which is really really cool.

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

Archives

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: