How to check if an array is empty in javascript
How do we check to see how many elements are in an array?
We can use the length
property of the type Array
.
const arr = [1,2,3]
console.log(arr.length) // 3
We see that the printing out arr.length
equals 3 because there are 3 elements in our array.
Empty would mean we should not have any elements in our array at all.
const emptyArr = []
console.log(arr.length) // 0
In order to check if our array is empty, we would need to see if the length equals 0
. We can write an if statement similar to below
if (arrayName.length === 0) {
// if my array is empty then do this
}