If I have an undeclared variable and use typeof
it tells me it\'s undefined
.
But if I then check it using if (qweasdasd === undefined)
You have an undefined variable, but not an undefined object value.
console.log(variable) // undefined
console.log(typeof variable) // "undefined"
console.log(variable === undefined) // Reference error
variable = undefined ;
console.log(variable === undefined) // true
typeof
is an operator that returns you a string indicating the type of the unevaluated operand. It doesn't matter if the unevaluated operand is undefined or not.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
>>> if (a !== 'undefined');
Exception: ReferenceError: Can't find variable: a
>>> if (typeof a !== undefined);
undefined
>>> if (typeof a !== void 0);
undefined
Trying to access undefined variable in Javascript gives ReferenceError
. typeof
is working because it not accessing variable value. Its checking its type.
typeof not requires defined variable. Its parameter should be an expression representing the object or primitive whose type is to be returned.
Trying to read the value of an undeclared variable (which you have to do before you can compare that value to the value of undefined
) throws a ReferenceError.
Applying the typeof
operator to an undeclared variable does not.
I think I have a very simple explanation for this -- because the specs say so:
- If Type(val) is Reference, then
a. If IsUnresolvableReference(val) is true, return"undefined"
.
- Let lval be GetValue(lref).
[And inside the definition of GetValue we have]
- Let base be the result of calling GetBase(V).
- If IsUnresolvableReference(V), throw a ReferenceError exception.
typeof
looks like a function call, but it is not - it is an operator. Operators are allowed to break rules. typeof(qweasdasd)
does not assume qweasdasd
exists; whether it exists or not and what it is is what typeof
exists to discover. However, when you test qweasdasd === undefined
, you are using qweasdasd
as a value, and JS complains when you use a variable that you haven't assigned a value to.