Undefined - JavaScript - MDN Web Docs - Mozilla

typeof operator and undefined

typeof can also determine whether a variable is undefined:

jslet x; if (typeof x === "undefined") { // these statements execute }

One reason to use typeof is that it does not throw an error if the variable does not exist in the current scope.

js// x has not been declared before // evaluates to true without errors if (typeof x === "undefined") { // these statements execute } // Throws a ReferenceError if (x === undefined) { }

It also works with variables declared with var after the check, because the declaration is hoisted to the top of the scope with value undefined.

jsif (typeof x === "undefined") { // these statements execute } var x = 1;

This technique is usually only useful for testing global variables. You can know if a variable exists at any other scope (blocks, functions, modules, etc.) just by looking at the source code. 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, such as by using the in operator:

jsif ("x" in window) { // These statements execute only if x is defined globally }

However, none of the techniques above work if the variable is declared with let, const, or other lexical declarations. Using typeof before the line of declaration still produces a ReferenceError, due to the temporal dead zone (TDZ).

jsif (typeof z === "undefined") { // Uncaught ReferenceError: Cannot access 'z' before initialization } let z = 1;

Furthermore, let and const declarations do not create properties on the global object, so they cannot be checked with the in operator either.

jslet z; if ("z" in window) { // false, even if z is declared globally with let or const }

If you want to share global variables across different scripts, it is more advisable to use var or explicitly attach them to the global object:

jswindow.myGlobalVar = "foo";

Tag » When Is A Function Undefined