tags:

views:

39

answers:

2

I'm trying to check for if my object literal is not in my page.

var today = { 
      okay : true 
   }

If this snippet is not in my page I want to check for null or undefined but it kills silently...

 if (today.okay == null)
 if (today.okay == undefined) 

What to do?

+4  A: 

The reason it fails (it shouldn't be failing silently, it should be throwing an exception) is that you're trying to retrieve a value from a symbol (today) that may not be defined.

Try this:

if (typeof today == 'object' && today.okay) {
    // It's there
}
else {
    // It's not there
}

Alternately, of course, you can just handle the exception:

try {
    if (today.okay) {
        // 'today' is defined and 'okay' is truthy
    }
    else {
        // 'today' is defined, but 'okay' is not truthy
    }
}
catch (e) {
    // 'today' is undefined
}

My impression is that most JavaScript engines are very fast when it comes to throwing exceptions (this is not true of all environments), but if you anticipate this condition being not unusual (not exceptional), then I would handle it with inline logic, not an exception. Exceptions are for exceptional conditions.

T.J. Crowder
+1, mostly because it looks like it's a slow morning for votes in the javascript tag :-)
Andy E
Exception handling is a little too much for this, rather common, property testing.
Marko Dumic
@Marko: Completely agree, even said so in my answer. :-)
T.J. Crowder
+2  A: 

Assuming you require the "okay" to be boolean, the expression you're looking for is:

('object' == typeof today && today.okay === true)​​​
Marko Dumic