Difference between some() and every() in javascript – Javascript array methods

Confused between the some() and every() methods of the Javascript array? Don’t worry. After reading this post, you won’t have any confusion between these two Javascript array methods.

Difference between Array.every() and Array.some()

In simple words, the every() method checks whether each element of an array is meeting the condition, whereas, the some() method checks if at least one element of the array is meeting the condition.

For example, If you have an array of ages and you want to check whether all the ages are over 20, then you can use every() method here. But, if you want to check if at least one age is greater than 20, then, in this case, you will use some() method.

Now, let’s see some code.

Use the every() method to check whether all the elements pass the condition.

<!DOCTYPE html>
<html>
<body>

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


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

<script>
const ages = [30, 35, 50, 55];
document.getElementById("demo").innerHTML = ages.every(checkAge);

function checkAge(age) {
  return age > 20;
}
</script>

</body>
</html>

Here, again I took an array of ages, but here, I am checking whether any age in the array is greater than 20. I passed the array and the function checkGreaterThan20() to the some() method. Since the array contains an element that is greater than 20, some() method returns true.

Output :

Use the some() method to verify if any element of an array passes the condition.

<!DOCTYPE html>
<html>
<body>

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


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

<script>
const ages = [18, 12, 28, 19];
document.getElementById("demo").innerHTML = ages.some(checkGreaterThan20);

function checkGreaterThan20(age) {
  return age > 20;
}
</script>

</body>
</html>

Here, again I took an array of ages, but here, I am checking whether any age in the array is greater than 20. I passed the array and the function checkGreaterThan20() to the some() method. Since the array contains an element that is greater than 20, some() method returns true.

Output :

That’s about the difference between the JavaScript Array some() and every() methods.

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: