Coming from a non-javascript background, I'm trying to wrap my head around 'undefined'. I wrote a "isUndefined" function as follows:
function isUndefined(value) {
return (typeof value === 'undefined');
}
if I type in my source this (where the variable 'boo' does not exist), I get the expected result "undefined variable".
if (typeof boo === 'undefined') {
console.log('undefined variable');
}
if I type in the following:
console.log (isUndefined(undefined));
I get the expected result 'true'
If I type in: console.log(isUndefined(boo));
I get:
Reference Error: boo is not defined.
I expected to get 'true' - so my question is why does the first 'direct' check for undefined return the expected result, but a function() testing for it does not?
There is a difference between an existing variable that happens to contain the undefined
value, and a variable that does not exist at all. If a variable name doesn't exist, then it's an error to try to reference it.
The typeof
operator is a special case: it does accept a name even if there is no such variable of that name. But only when the name is actually used with the typeof
operator.
In your function example, you use a name that does not exist, and there's no typeof
operator at the point where the name is used. That's where the error occurs. It doesn't matter that you are passing the name into a function that will use typeof
; that function never gets called because the error has already happened.
Your function would work as expected if you give it an existing variable name. Then it would tell you if that variable has the undefined
value or not:
var boo; // now boo exists but has the undefined value
console.log( isUndefined(boo) ); // will log 'true'
If you were checking a global variable, it would work if you said window.boo
instead of just boo
. That's because it is not an error to reference a nonexistent property of an object; it just gives you the undefined
value when you do this:
// logs 'true' if there is no global 'boo'
console.log( isUndefined(window.boo) );
That wouldn't work if you wanted to check whether a local variable exists, though, because it won't be a property of the window
object.
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