Borislav Hadzhiev
Sun Oct 10 2021·2 min read
Photo by Yukie Emiko
To create an array if it doesn't exist:
undefined
or if
the variable doesn't have a type of 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.
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.
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.