Create an Array if it Doesn't Exist in JavaScript


Borislav Hadzhiev

Last updated: Oct 10, 2021


Photo from Unsplash

Create an Array if it Doesn't Exist #

To create an array if it doesn't exist:

  1. Check if the type of the variable is equal to the string undefined or if the variable doesn't have a type of array.
  2. If either of the conditions are met initialize the variable as an array.
if (typeof arr === 'undefined' || !Array.isArray(arr)) { var arr = []; } console.log(arr); // 👉️ [];

In the example we first check if the variable arr has a type of undefined.

The typeof operator doesn't throw an error if we use it on a variable that's not declared.

If the variable arr has a type of undefined, we know that we have to create the array.

Then we use the || (OR) operator to add another condition. If we reach this point, we know that the arr variable is declared.

In the second condition, we check if the variable is NOT of type array.

If it is of type array, we don't want to re-create the array, however if it isn't of type array, we create the array in the if block.

If either of the conditions evaluate to true, the if block runs and we declare the variable and set it to an empty array.

Note that we intentionally use the var keyword, instead of the block scoped let and const because we want the arr variable to be accessible outside the if block.

The only way for this approach to fail is if you had previously declared the arr variable using const. In this scenario we would not be allowed to re-declare an already declared using const.

If you had previously declared the variable using let, you can simply do the following check:

let arr; if (!Array.isArray(arr)) { arr = []; } console.log(arr); // 👉️ [];

In this scenario, we know that the arr variable has been declared, so we don't have to use the typeof operator to avoid getting an error.

We don't use the var keyword either, we just change the value of the arr variable if it isn't an array.

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.