JavaScript Code

JavaScript Array every()


every() – Check if every element of array satisfies a condition

array.every( function, thisValue )
  • array is the given array
  • every is inbuilt array method name
  • function a function to run for every element. the definition of the function is function(element, index, arr). the function must return a boolean value of true or false
    • element is the current element in the array
    • index of the current element [optional argument]
    • arr is the array of current element [optional argument]
  • this is a value passed to the function as its this value [optional argument]

every() method returns true if all the elements of the array return true for the given function. if there is at least one element that returns false, then every() method returns false for the array

Examples

1. check if all the strings in the given array fruits are non-empty

function isNonEmptyString(x) {
    if (x.length != 0) {
        return true;
    } else {
        return false;
    }
}

let fruits = ['apple', 'banana', 'cherry'];
let output = fruits.every(isNonEmptyString);
console.log(output);

2. fruits have an empty string. check if the output of every() if the function returns false for an empty string

function isNonEmptyString(x) {
    if (x.length != 0) {
        return true;
    } else {
        return false;
    }
}

let fruits = ['apple', '', 'cherry'];
let output = fruits.every(isNonEmptyString);
console.log(output);

3. check if all the numbers in array are even

function isEven(num) {
    if (num % 2 == 0) {
        return true;
    } else {
        return false;
    }
}

let numbers = [4, 10, 8, 18];
let output = numbers.every(isEven);
console.log('Are all numbers even? : ' + output);

Copyright @2022