Can this code
if (typeof foo != "undefined" && foo !== null) { }
be safely refactored into this code?
if (foo != null) { }
Is it the exact same thing? (And if not, how is it different?)
Not really. You'll get thrown a ReferenceError
exception in your second example if foo
has not been declared.
On the other hand, you can safely check for undefined non-declared variables with the typeof
operator.
A simple experiment will answer this question:
if( foo != null ) {
alert('foo not null');
}
the above example yields a javascript error in many browsers: "ReferenceError: Can't find variable: foo"
. This is because we've used a variable that has not been previously declared as an argument or var
in current scope.
the typeof
operator, on the other hand, makes an explicit accommodation for variables that haven't been defined -- it returns 'undefined'
, so:
if( typeof foo != 'undefined') {
alert('foo is not defined');
}
works as expected.
So the answer is "no" -- they are not the same thing -- though in some javascript environments they may behave the same way, in other environments your second form will produce errors when foo
is not defined.
Variables can actually hold the value undefined
, which is the default value if a variable has never been assigned to. So foo != null
will work if your variable is declared using var
or given a value through assignment, but if it isn't, you will get a ReferenceError. Therefore, the two snippets are not equivalent.
If you can be sure that foo
is declared, this is safe and easier to understand than your original second snippet, assuming that nowhere in the code something like undefined = 42
exists:
if(foo !== undefined && foo !== null) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With