Hacker News new | past | comments | ask | show | jobs | submit login

I usually write an isDefined() in JavaScript projects. Testing for typeof foo !== 'undefined' makes me want to vomit.

I completely agree with you, but I would use "foo === undefined" for locals and "this/window.foo === undefined" for globals. You can also test for "== null", if you don't care for null values.

Of course due to a bug in the old (v3) spec, you could redefine the builtin undefined as well as some other builtins like NaN and Infinity, but you shouldn't really be doing that and the spec at least is now fixed.

In the meanwhile, to fight that, this is a commonly used pattern for browsers: (function(window,undefined) {

// code //


I did the same; I had a simple "def()" and "undef()" function pair, which shrank the code base a tiny bit and made it terribly easy to understand what conditions I was testing for.

Unfortunately, I recently profiled my code and found that those functions were being called an absurd number of times during a moderately complicated page load, so they're gone now. :-(

Yeah. Although, in modern browsers, the overhead is really trivial.

I just tried timing it in modern Chrome. The overhead of calling a function like isDefined(), versus typeof x !== 'undefined', seems trivial. On my machine, after 100,000 calls there's a difference of 50ms.

Still, I concede that there are some situations where it would matter, if you were driving an animation. And in older browsers it might matter a lot even in other circumstances.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact