Reputation: 15685
I asked a question about the undefined value in javascript a few days ago. (What is the best way to compare a value against 'undefined'?)
I conclude that it is a bad practice to do !== undefined
as undefined
can be set to 'another' value.
undefined='foo';
var b;
(b !== undefined) // true
I gave a quick look at the jquery code, I realized that in every part, the author use !== undefined
and not typeof var !== "undefined"
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
Is it a possible mistake? Even if I know that we should be crazy to reassign the value of undefined - for the most popular library I think it can cause some mistakes...
Who is in the right way?
Upvotes: 2
Views: 4798
Reputation: 707328
If you reassign undefined
to something else and you expect to use a large library, then you get what you deserve as far as I'm concerned. It's perfectly OK to test if a variable is undefined
and jQuery needs to do that in many cases to tell which optional parameters are or aren't passed to various functions.
Upvotes: 1
Reputation: 99911
undefined
in the jQuery code is actually an undefined parameter of a function wrapping the whole code:
(function(window, undefined) {
// jQuery code here
// undefined is the undefined parameter
}(window)); // notice we don't pass a second argument here
That's perfectly safe, as the undefined
parameter is local to the function, and nobody except the code in this function can assign to it.
Using a more clear syntax:
var myFunc = function(window, undefined) {
// jQuery code here
// The undefined variable is the undefined parameter
// If the function has been called without a second argument,
// then the undefined parameter is undefined.
};
myFunc(window); // no second argument
Upvotes: 12