• Register
36,800 points
11 5 4

In this tutorial you will learn how to use the JavaScript methods: Array.every () and Array.some ().

Array.every()and they Array.some()are JavaScript methods that help us check if a specific condition is met in an array or matrix . We'll look at Array.every () first and then we'll look at Array.some ().

Javascript Array.every () method:

There is a simple concept of Array.every()what it is, if each element in the array meets the condition, then Array.every () returns true.

The Array.every()JavaScript method takes a callback function as an argument.

Let's see how Array.every () works, suppose we have an array that has the following values:

let numbersewg = [1,5,8,2,4,7];  

And we have to check if the array values ​​are less than 10. A simple way to check this is to iterate over each element and compare it to the number 10 and return true or false. With Array.each () we can do it like this:

function testNumber(element) { 
    return element < 10; 
} 
numbersewg.every(testNumber) 

//return true

JavaScript Array.some () method:

The method Array.some()is the same as Array.every()but, as the name suggests, if there are any elements, it returns true.

If we wanted to validate that some numbersewg array element is greater than 10, the method Array.some() returns false , since none of the elements in the numbersewg array is greater than 10. But if we check if any number is greater than 4, then it returns true as shown. shows below:

function testNumber(element) { 
        return element > 4; 
} 
numbersewg.some(testNumber) 

// return true; 

We can also use the arrow function with Array.some()and Array.every()as follows:

numbersewg.every( element => element > 10) 
// return true

Check if a value exists in an array with JavaScript

function testNumber(element) { 
    return element == 8; 
} 
numbersewg.some(testNumber) 

//return true

I hope it has been clear and if you have questions or comments write me in the comments section.

    36,800 points
    11 5 4