Borislav Hadzhiev
Mon Apr 25 2022·2 min read
Photo by Benjamin Balázs
Updated - Mon Apr 25 2022
To check if an array is empty access its length
property, e.g. arr.length
.
If an array's length is equal to 0
, then it is empty. If the array's length is
greater than 0
, it isn't empty.
const arr = ['hello']; if (arr.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }
The if
block will only run if the array's length is greater than 0
. If the
array's length is greater than zero it contains at least 1
element.
Alternatively, you can use
optional chaining operator ?.
to avoid an error if variable storing the array is set to undefined
or null
.
// Not supported in IE 6-11 const arr = ['hello']; // 👇️ Use ?. if (arr?.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }
This code snippet is different from the first one because even if the arr
variable was set to undefined
or null
we wouldn't get an error when we try
to access the length
property on the array.
let arr = undefined; if (arr?.length > 0) { // if this code block runs // 👉️ arr is not empty }
undefined
or null
value it just short-circuits and returns undefined
, instead of throwing an error.If you're unsure whether the variable stores an array, you can check for the
type of its value before accessing its length
property.
let arr = ['hello']; if (Array.isArray(arr) && arr.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }
We have 2 conditions in the if
statement. We used the &&
(and) operator to
signify that both conditions have to be satisfied for the if
block to run.
We first check if the arr
variable stores an array and then check if the
array's length is greater than 0
.
This approach is similar to the optional chaining one, but I prefer it because:
arr
is
set to a string
. Strings in javascript also have a length
property.