Javascript Array every() method

In this post, I will tell you about a very useful Javascript Array method. So, without further ado, let’s begin.

Array.every() method in javascript

Let me ask you a question. How would you check whether the marks of all the students in an array are greater than 80? You have to return true if all the elements of the array pass the condition. If any single element does not pass the condition, return false. How would you do that?

You would probably use for loop to compare the elements of the array. But, there’s another method to do the same. And the method is javascript Array. every() method. You can check if all the marks in the above array are greater than 80 by using the Array. every() method. Lets’ see the syntax of the every() method.

array.every(function(currentValue, index, arr), thisValue)

Now, let me give you an example code to make it more clear to you.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Array every() method</h1>

<p id="demo"></p>

<script>
const marksArray = [85, 90, 95, 90];
document.getElementById("demo").innerHTML = marksArray.every(checkMarks);

function checkMarks(marks) {
  return marks > 80;
}
</script>

</body>
</html>

Here, I have taken an array marksArray that contains the marks of all the students. I have defined a function to pass as a parameter to the every() method. The every() method will call this function for each element of the marksArray. If all the elements pass the condition, i;e if the method checkMarks returns true for all the elements, then, the every() method returns true. If the checkMarks method returns false for an element, then the every() method returns false.

Output :

You can see the output is true because all the marks in the array are greater than 80.

Let’s see the parameters of the every() method.

function() – It is the required parameter. It is the function the every() method call for each element of the array.

currentValue – It is also a required parameter. It is the value of the current element.

index – It is an optional parameter. It is the index of the current element.

arr – It is also an optional parameter. It is the array of the current element. (You have already called the method on the array that contains the current element).

thisValue – It is an optional parameter. It is the value passed to the function to use as this while executing the function.

That’s about the Javascript Array every() method.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: