← Back to context

Comment by ootachi

14 years ago

"if (typeof my_var !== "undefined" && my_var !== null) { // you idiots put Rasmus Lerdorf to shame }"

Someone doesn't know about the "foo == null" idiom (it's true if and only if x is null or undefined).

Not to mention the fact that the "typeof foo == 'undefined'" thing is overly defensive "best practice" that people keep needlessly repeating, IMO. If someone is stomping all over important fields of the global object, there's nothing you can do.

JavaScript has its issues, but this one isn't fair.

> Someone doesn't know about the "foo == null" idiom (it's true if and only if x is null or undefined).

(preface: I am by no means a javascript guru)

Really? Double equals in javascript? I thought that was a no-no due to the type coercion that "==" does.

I get a reference error when I crack open a console and try your example idiom.

  • Right, it doesn't work when you're testing whether foo is a bound name at all. In that case you need to use "window.foo" (or this.foo in Node).

    And yeah, it's double equals. The coercion is exactly what allows "== null" to do the right thing in the presence of undefined. Contrary to popular belief, "0 == null", "'' == null", and "[] == null" are all false in JavaScript. "foo == null" doesn't test for falsiness, it just checks whether foo is null or undefined.