JavaScript empty array | Check and Clear Examples

You can check JavaScript empty array doing by check for undefined first and then the length of it, if the length is zero then the array is empty.

If you want to clear/empty an array in JavaScript, then there are multiple ways to it like Substituting with a new array, Setting the length prop to 0, Splice the whole array, etc.

The simple, easy and safe way to do it is:

Example of check JavaScript empty array

First, check undefined in if statement. If the first condition true then check array length.

If you do it the other way round, it will generate an error if the array is undefined.

If you want to check undefined condition also then use (===) equality operator for it.

Let’s see the example of Check if array has empty values JavaScript.


JavaScript empty array

Examples of doing empty an array in JavaScript

There are multiple ways to do it, let’s see one by one:-

Substituting with a new array

Output: Empty array

empty an array in JavaScript

Setting length prop to 0

This will clear the existing array by setting its length to 0.

Splice the whole array

This will remove all elements from the array.

Read more about it: Remove element from Array JavaScript

Using Loops

 It is the slowest solution.

Q: How to Declare an empty array in JS?

Answer: Simple see below code:-

Do comment if you have any doubts and suggestion on this question. Let’s us know which one is best way to do it.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.