Reputation: 3797
For a variable x, let typeof x === 'undefined'
I have written a function which checks whether variable is undefined
or not
var isUndefined = function(obj){
return typeof obj == 'undefined';
};
Here are two scenarios :
console.log(typeof x === 'undefined') // returns true
isUndefined(x) // throws this error ReferenceError: x is not defined
Why I cant pass an undefined variable here?
Upvotes: 6
Views: 31398
Reputation: 4259
Variable x
is not declared but you are asking typeof
in global context
typeof x === 'undefined' // Returns true
Which is equivalent to below
typeof window.x === 'undefined' //True
But the below code
x === undefined //Throws error
And
x in window //Throws Error
as the variable is never set or declared in the global scope with any standard JavaScript datatypes.
Read MDN blog, Which states that :
JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object
Now when calling the isUndefined
function you will be passing the reference of the variable x
which is not declared in the parent scope and runs the code in functional scope trying to take the reference of x
.
As x
is no where declared, there is no meaning or value to be passed by javascript interpreter at runtime to isUndefined
. Hence throws the Reference error asking the develeper to atleast declare the variable which when not assigned any value will be set default to primitive type undefined
.
Now by setting x to primitive type undefined explicitly as below
var x; // Equivalent to window.x
or
var x = undefined; //Equivalent to window.x = undefined
Now the JavaScript interpreter is aware that there a variable called x
declared in global scope window
and is set to primitive datatype. Below statements become true
:
typeof x === 'undefined' // Returns true
x === undefined //Returns true
x in window // Returns true
isUndefined(x) // Returns true
Upvotes: 1
Reputation: 424
See this post. You have to understand the difference between undefined and undeclared variables.
At least you would do:
var x; //undefined until assignment;
isUndefined(x); // returns true;
Upvotes: 4
Reputation: 11420
Basically, undefined represents value, which are not defined formally by user. Consider your example :
var isUndefined = function(obj){
return typeof obj == 'undefined';
};
So, isUndefined()
when invoked without any argument, then the value of obj will be undefined in the function.
Upvotes: 1