Hacker News new | ask | show | jobs
by ricklancee 3994 days ago
Shouldn't the undefined check be like this?

    if (typeof fruit === "undefined") {
       fruit = "strawberry";
    }
Unless your doing something like:

    (function(undefined) {

    })();
2 comments

`typeof` is useful when the binding may or may not exist at all, this is almost exclusively an issue with global variables which may not be there (toplevel APIs or libraries missing).

If the binding exists at all, you can just check for its value. And parameters always create a binding pretty much by definition.

So no, there is no reason to use `typeof` to check whether a parameter is `undefined`.

If you fear that somebody rebound the global `undefined` for some insane reason, you can use `void 0` instead.

In ES5+, the global `undefined` is immutable, so it should be pretty safe unless someone declared a local `undefined` var in an outer scope.
I use "var undef;" at the top of a function and never set it to a value. Comparison with === is the same as with undefined. And it's nice for minification.