How to Check if Array is Empty in JavaScript: Simple Guide
To check if an array is empty in JavaScript, use the
length property and compare it to zero, like array.length === 0. If the length is zero, the array has no elements and is empty.Syntax
Use the length property of an array to find out how many elements it contains. If the length is zero, the array is empty.
array.length: Returns the number of elements in the array.- Check if
array.length === 0to confirm emptiness.
javascript
if (array.length === 0) { // array is empty }
Example
This example shows how to check if an array is empty and print a message accordingly.
javascript
const fruits = []; if (fruits.length === 0) { console.log('The array is empty'); } else { console.log('The array has elements'); }
Output
The array is empty
Common Pitfalls
Some common mistakes when checking if an array is empty include:
- Using
array == nullorarray === nullwhich only checks if the array variable is null or undefined, not if it has elements. - Checking if the array itself is truthy or falsy, which is always true for arrays even if empty.
Always check the length property to determine emptiness.
javascript
const arr = []; // Wrong way: if (!arr) { console.log('Array is empty'); // This will NOT run because arr is truthy } // Right way: if (arr.length === 0) { console.log('Array is empty'); }
Output
Array is empty
Quick Reference
Summary tips for checking if an array is empty:
- Use
array.length === 0for a clear and reliable check. - Do not check the array variable itself for truthiness or null.
- Remember that an empty array is still an object and truthy in JavaScript.
Key Takeaways
Check if an array is empty by testing if
array.length === 0.Never rely on truthy or falsy checks to determine if an array is empty.
An empty array is still truthy in JavaScript, so always use the length property.
Avoid checking if the array variable is null or undefined to test emptiness.
Using
length is the simplest and most reliable method.