|Table of Contents|
|METHOD: 01 Use Typeof Operator and Length Property|
|METHOD: 02 Use Array.isArray(), Typeof Operator and Length Property (Recommended)|
METHOD: 01 Use Typeof Operator and Length Property
The following method is very commonly used by numerous developers. So let’s check an array is empty or not.
This method has one drawback. If you pass any non-empty string then it will pass the test which is wrong, so for that we have to use Method 2 but to understand Method 2, you should try & test Method 1.
On the above example, we have added typeof operator to check the data type of variables so if your array is not defined, then it will return an
undefined string that means your array is not present into the script but if it exists then it will return an array or object as a string. You can test typeof operator like this
alert(typeof devices);, it will alert the object or array string.
Then we have added
array.length > 0 to check the length (number of elements) of the array which ensure that an array is not empty or not null.
To test the above example with an empty array
let devices = ; and then try to remove whole devices array that will produce an undefined error, but the above example will pass that too and return with “array is empty”.
For further testing, you can also remove the typeof condition and test it with your browser’s console. It will generate the undefined error.
METHOD: 02 Use Array.isArray(), Typeof Operator and Length Property (Recommended)
We are recommending you to use this method. Try to play with the above example as we mentioned in Method 1 and let us know if you found anything wrong with the example so that we can improve further and update the post.
Additionally, read our guide:
- How To Check If An Element Is Hidden In jQuery
- jQuery Form Submit With Examples
- AJAX PHP Post Request With Example
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂 Keep Smiling! Happy Coding!