check if array is empty javascript

It is possible to check if an array is empty in JavaScript by using the length property of the array. This property returns the number of elements in the array. If the array is empty, then the length property returns 0.


// Check if an array is empty
let array = []

if (array.length === 0) {
    // array is empty
    console.log('array is empty')
} else {
    // array is not empty
    console.log('array is not empty')
}

If you want to check if the array is empty without using the length property, you can use the every() method. This method applies a function to each element in the array and returns true if all elements return true. If you pass in an empty array, then it will always return true.


// Check if an array is empty
let array = []

if (array.every(Boolean)) {
    // array is empty
    console.log('array is empty')
} else {
    // array is not empty
    console.log('array is not empty')
}

Finally, you can use the some() method. This method is used to check if at least one element in the array returns true. If you pass in an empty array, it will always return false.


// Check if an array is empty
let array = []

if (!array.some(Boolean)) {
    // array is empty
    console.log('array is empty')
} else {
    // array is not empty
    console.log('array is not empty')
}

In conclusion, there are several different ways to check if an array is empty in JavaScript. You can use the length property, every() method, or some() method to determine if an array is empty.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe