Richard
Richard

Reputation: 5089

Javascript module pattern with undefined specified

I believe jQuery uses undefined in the module pattern to avoid it being redefined to an unexpected value. I thought about doing this but whenever I compare undefined I tend (always?) to use

typeof foo === 'undefined'

So is there any point doing this:

(function (win, doc, RG, undefined)
{
  // App goes here

})(window, document, typeof RGraph === 'object' ? RGraph : {});

Upvotes: 0

Views: 561

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74204

There are three ways to test whether a value is undefined:

Method 1: Use typeof:

if (typeof value === "undefined") {
    // do something
}

Method 2: Compare it with the variable undefined:

if (value === undefined) {
    // do something
}

Method 3: Compare it with void 0:

if (value === void 0) {
    // do something
}

Q: Which one should you use?

A: There are many factors to consider:

  1. In terms of understandability typeof and undefined are the best.
  2. In terms of minimum characters undefined is the best when minified.
  3. In terms of performance (http://jsperf.com/type-of-undefined-vs-undefined):
    1. Both undefined and void are at par in most browsers (notably Firefox and Chrome).
    2. In Chrome typeof is slower than the other two but in Firefox it is the fastest.
  4. Using typeof is the only way to test whether or not a variable exists.

Based on these factors I would say that undefined (method 2) is the best method. There's always the problem of undefined being overwritten. However if you're using the module pattern (which you should be doing in the browser) then you can get undefined for free:

(function ($, undefined) {
    // you can use `undefined` safely here
}(jQuery));

Hence if you're using the module pattern then I would suggest you use the second method. It is readable, understandable and concise. The only disadvantage is that you won't be able to test whether or not a variable exists. However you can always fall back to typeof for that.

Upvotes: 0

Bergi
Bergi

Reputation: 664434

whenever I compare undefined I tend (always?) to use typeof foo === 'undefined'

Well if you don't use undefined in your module then there is no point in declaring it as a parameter to ensure its value.

However, there's a question mark after your "always", and you can hardly know who else might work with your code in the future, so it still might be advisable.

Upvotes: 1

Related Questions