There are 2 ways to easily check if array is empty in JavaScript where most of them are 1 liner code. Let’s explore the methods.
Methods to Check if Array is Empty in JavaScript
Here are the list of 2 methods where we can check if an array is undefined
, null
or empty. Since each of them have their own properties and features, we can choose which to use depending on our needs.
- Array
isArray()
with.length
Method - Array
undefined
with.length
Method
Let’s look into each details with illustration below.
1. Array isArray()
with .length
Method
is part of original Array standard built-in object method in JavaScript. It takes in any object to check if the value is an array.
()isArray
Its features includes:
- Validate if pass-in value is an array
- Does not change the original array
Below shows the example where we are using isArray()
method. It will return true
as long as it is an array object. Then we top up with .length
to check the size of array.
// The below execution returns true Array.isArray([]); Array.isArray(['one', 'two', 'three']); Array.isArray(new Array()); // The below execution returns false Array.isArray(undefined); Array.isArray(null); Array.isArray(false); const myArray = ['one', 'two', 'three']; if (Array.isArray(myArray) && myArray.length !== 0) { console.log('myArray Exist!') } // myArray Exist!
2. Array undefined
with .length
Method
Since an array is a referencer by pointer, we will be able to check if the array is undefined or null before checking the length.
Below shows the example that by combining array pointer checking and .length
method, we can check them by using the &&
operator so that if the first condition is not match, execution will stop there.
const myArray = ['one', 'two', 'three']; if (myArray !== undefined && myArray !== null && myArray.length !== 0) { console.log('myArray Exist!') } // myArray Exist!
Conclusion
We have look into 2 different methods to check if array is empty in JavaScript. Both of the above methods are simple but isArray()
will be able to check for more information.
No Responses Yet