T
Thomas 'PointedEars' Lahn
Bart said:Well...
I'm wondering why in the original question
if (x == null) {
doStuff(x);
}
won't do.
Keep in mind that the original question was “What's the ‘best’ way to
determine if a variable is defined?†If "defined" is understood as "does
not throw a ReferenceError exception with message ‘... is not defined’, then
the following applies:
If `x' was not declared a variable (and so that variable was not defined),
evaluation of your comparison would throw a ReferenceError. Not so with
`typeof', but that comes at a price: With `typeof' you cannot determine
whether the property referred to by the /Identifier/ was declared a variable
(a property of a Variable Object with the attribute DontDelete).
If `x' was declared and implicitly initialized with `undefined' --
var x;
-- or `null' --
var x = null;
-- or assigned `undefined', e.g.
var x = void 0;
-- doStuff() would be called anyway with your code as `undefined == null'
(it is a type-converting comparison).
ISTM the only way to determine whether an identifier is available is to try
and catch possible ReferenceError exceptions. And without static code
analysis there appears to be no way of determining if an identifier has been
declared a variable but that variable has not been initialized (as it may
have been explicitly initialized with `undefined' or assigned that value
after initialization, but before the test.)
PointedEars