JavaScript Code


How to check if array is empty in JavaScript?


Check if array is empty in JavaScript

In this tutorial, you are given an array. Write a JavaScript program to check if the array is empty.

Solution

An array is empty if there are no elements in it. If there are no elements in array, then the length of such array would be 0. So, to check if an array is empty, we have to check if the length of the given array is 0. To get the length of the array, we can use Array.length property, and to compare this length with 0, we can use comparison equal-to operator.

Program

1. In the following program, we are given an array in fruits. We shall check if the array fruits is empty.

let fruits = [];
if ( fruits.length == 0 ) {
    console.log('empty array');
} else {
    console.log('not an empty array');
}

Since the array is empty, if-block must run.

2. Now, take some elements in fruits array and check the output of the program.

let fruits = ['apple', 'banana', 'mango'];
if ( fruits.length == 0 ) {
    console.log('empty array');
} else {
    console.log('not an empty array');
}

Since the array is not empty, else-block must run.



copyright @2022