You will find it helpful because you may end up in a position where you want to disable a button whenever the array is empty and enable it if the array is not empty, there are many more such scenarios of it where you will find it helpful.
Well, how do we get to know if an array is empty or not, we just check if there are any element in it or not, if there are no element then surely the array is empty.
The length property returns the length of the array by which you can determine whether the array is empty or not. This property is directly used with the name of array concatenated by dot (.) operator, e.g.
But there is one problem with length property that it can be used on other data types too. For example, if there is an empty string
str = " ", then if we try the length function
str.length the answer returned will be 0 i.e. empty.
Array.isArray() method to confirm it. This method helps to determine that the value you have passed in this function is array or not. So, this will help us in identifying the array.
- Check if the given variable is an array or not.
- If above step is true, then find the length of the array else print given variable is not an array.
- Check if the length of the array 0 or greater than 0.
- If the value is 0 print array is empty, or else print array is not empty.
Output : Given array is not empty
Given Array is empty
Given variable is not an array
Well, you can check if the array is empty or not in just one line of code. All you have to do it to write all of these a single line using
&& (and) logical operator. It is shown below.
if(Array.isArray(arr1) == true && arr1.length == 0) if this holds true then the given input is an array and it is also empty, else the input is not an array or input is an array but not empty.