How to Check for Undefined in JavaScript
The typeof
keyword returning "undefined"
can mean one of two things: the variable is the primitive undefined
, or the variable has not been declared at all. Here’s how to tell the difference.
What if a JavaScript value is undefined
?
In JavaScript programming, you will encounter the primitive data type undefined
, which indicates the absence of a value.
“The global
undefined
property represents the primitive valueundefined
. It is one of JavaScript's primitive types.” — MDN Docs
JavaScript variables start with the value of undefined
if they are not given a value when they are declared (or initialized) using var
, let
, or const
.
Variables that have not been declared usually cannot be referenced, except by using the typeof
keyword, which will not throw a ReferenceError
.
How to check for an undeclared variable?
The typeof
keyword will return "undefined"
for undeclared variables as well as for any variable containing the value undefined
.
“A variable that has not been assigned a value is of type
undefined
.