Check if all the strings in array are non-empty in JavaScript
In this tutorial, you are given an array of strings. You should write a JavaScript program to check if all the strings in the given array are non-empty.
Solution
The length of a non-empty string is greater than 0. To check if all the strings in the given array are non-empty, call every() method on this array, and pass a function that returns true for a non-empty string, or false otherwise.
Program
fruits
is the given array of strings. isEmpty
is the function that checks if a given string is non-empty or not. every()
method checks if every element in the fruits
array is non-empty.
function isNonEmpty(str) {
if (str.length > 0) {
return true;
} else {
return false;
}
}
let fruits = ['apple', 'banana', 'cherry'];
let output = fruits.every(isNonEmpty);
console.log('Are all string non-empty? : ' + output);
You may take some empty strings in fruits
array, and check the result.