if (typeof foo !== 'undefined') {
// Now we know that foo is defined, we are good to go.
}
The typeof
evaluates to true
or false
based on whether the variable foo
is defined or not.
But, say if foo !== 'undefined'
evaluates to true
, then typeof
of true
should evaluate to 'boolean'
.
Why does it evaluate to true
or false
?
Because precedence rules for the typeof
and inquality operators define that that expression is parsed as
(typeof foo) !== 'undefined'
For more information, see the MDN page on operator precedence. typeof
is precedence 16; inquality is precedence 10. The higher precedence of typeof
means that it "binds" more tightly to its operand.
By the way, why do you have undefined variables in your code?