javascript: Say something about undefined

I find people treat undefined incorrectly a lot. It’s a value, you can use it, test for it, etc, but people frequently use typeof x == "undefined" when they don’t need to.

I made a fork with a big changeset of my own opinions, but here’s the section I wrote about undefined:


## <a name='undefined'>undefined</a>

  - `undefined` is an object.  You should use it as an object.  You can test for it.  For instance:

    ```javascript
    // good
    function pow(a, b) {
      if (b === undefined) {
        b = 1;
      }
      return Math.pow(a, b);
    }

    // bad
    function pow(a, b) {
      if (typeof b == "undefined") {
        b = 1;
      }
      return Math.pow(a, b);
    }
    ```

  - *Only* use `typeof x == "undefined"` when the variable (`x`) may not be declared, and it would be an error to test `x === undefined`:

    ```javascript
    if (typeof Module == "undefined") {
      Module = {};
    }

    // But also okay, for browser-only code:
    if (window.Module === undefined) {
      Module = {};
    }
    ```

    Note that you can't use `window` in Node.js; if you think your code could be used in a server context you should use the first form.

About this issue

  • Original URL
  • State: open
  • Created 11 years ago
  • Reactions: 2
  • Comments: 26 (1 by maintainers)

Most upvoted comments

The reason why comparision to undefined is not practiced, is that in most old browser engines you can overwrite it:

window.undefined = 'foo';
alert('foo' === undefined); // true

Therefore it’s not safe. Imagine also small mistake in a code that inserts <div id="undefined"></div> to the document, after that all your undefined comparisons are doomed.