JavaScript Code

How to check if all the strings in array are non-empty?


Problem Statement

given an array of strings, 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



copyright @2022