Check if a Variable is Defined or Initialized in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Check if a Variable is Defined or Initialized #

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {}. If the the typeof operator doesn't return a string of "undefined", then the variable is defined.

index.js
let a; console.log(typeof a); // 👉️ 'undefined' // 👇️ the variable `b` is not declared in our code // but typeof doesn't throw an error console.log(typeof b); // 👉️ 'undefined' if (typeof a !== 'undefined') { // if this runs // 👉️ the variable has been declared }

We used the typeof operator to check if a variable's type is not equal to the string undefined.

The if block runs only if the variable has been declared.

Note that the typeof operator doesn't throw an error when used with a variable that hasn't been declared.

However, there is a scenario where the typeof operator would throw an error.

If we use the typeof operator before declaring a variable with let or const, we would get an error.

index.js
// 👇️ Throws an error // ⛔️ Cannot access 'a' before initialization if (typeof a !== 'undefined') { } let a;

We check if the variable a has been defined, before actually initializing it with the let keyword.

This causes an error because JavaScript assumes that we are trying to access a variable before initializing it.

The outcome would be the same if we defined the a variable using the const keyword.

However, the error would not occur if we declared the variable using the var keyword because of how hoisting works in JavaScript.

index.js
// 👇️ no error occurs if (typeof a !== 'undefined') { } var a = 10;
The reason the typeof operator doesn't throw an error in this case, is because, the variable a gets hoisted to the top and its value gets set to undefined.

The code sample above is the same as:

index.js
var a; if (typeof a !== 'undefined') { } a = 10;

The variable a is declared on line 1, however its value is set later on in the code because of how hoisting works in JavaScript.

You can check if an already declared variable is set to a truthy value with a simple if statement.

index.js
let a; if (a) { // this code runs if // the `a` variable is NOT // 👉️ 0, empty string, null, undefined, false or NaN }

The condition is only met if the a variable is declared and stores a truthy value.

If the variable is truthy the code in the if block runs.

Truthy are all values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.