Create an Array if it Doesn't Exist in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20212 min read

banner

Photo by Yukie Emiko

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.
index.js
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:

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee