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.

Dr. Derek Austin 🥳
Coding at Dawn
Published in
5 min readMar 5, 2020

--

Photo by Markus Spiske on Unsplash

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 value undefined. 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.

--

--

Dr. Derek Austin 🥳
Coding at Dawn

I write about real-world programming career advice, MongoDB vs. PostgreSQL, Git, React, JavaScript, VS Code, TypeScript, and Next.js. Doctor of Physical Therapy