Problem Statement
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. given an array fruits
. check if array fruits
is empty
let fruits = [];
if ( fruits.length == 0 ) {
console.log('empty array');
} else {
console.log('not an empty array');
}
if-block must run
2. take some elements in fruits
array and check the output
let fruits = ['apple', 'banana', 'mango'];
if ( fruits.length == 0 ) {
console.log('empty array');
} else {
console.log('not an empty array');
}
else-block must run