every() in JavaScript

every() in JavaScript

·

2 min read

Table of contents

No heading

No headings in the article.

The every() method in JS checks whether all of the elements of an array meet the condition that is passed inside the callback of every() function. This function returns a boolean value and returns true if and only if every element inside the array follows the test condition.

every() has mainly three arguments

  • element - current element which is being iterated over from the array.
  • index - index of the current element.
  • array - this is the name of the array on which every method is being performed.

Here is an example to understand it well,

let array = [2, 45, 12, 54, 67, 77];
array.every((element, index, arr)=>{
    console.log(element);
    //output - 2 (current element)
    console.log(index);
    //output - 0 (index of that current element)
    console.log(arr);
    //output - [ 2, 45, 12, 54, 67, 77 ] (the array)
});

Now below I am putting an example through which you can understand the functionality of the every() function.

let array1 = [2, 45, 12, 54, 67, 77];
var isDivisibleByTwo=
array1.every(element=>{
    return element%2 ===0;
});
console.log(isDivisibleByTwo);
//output - false

The output of the above code is false as not every element of array1 is divisible by 2.

Let's have one more example. The below example will check if all the elements of one array are in another array or not, using every().

let arr1 = [10,11,12,13,14,15]
let arr2 = [10,11,12]
let hasAll = arr2.every((element)=>{
    return arr1.includes(element)
})
console.log(hasAll);
//true