Skip to content

JavaScript Array Functions

Rhodin Emmanuel Nagwere edited this page Sep 21, 2022 · 2 revisions

some() and every() JavaScript Array functions

These help you test if something is true for every element or some elements of an array.

Example - every()

We need some data to test, consider an array of numbers;

const nums = [34, 2, 48, 91, 12, 32];

Now let's say we want to test if every number in the array is less than 100.

nums.every(n => n < 100);

// true => all numbers in the array are less than 100

How it works

  • every loops over the array elements left to right
  • For each iteration, it calls the given function with the current array element as its 1st argument.
  • The loop continues until the function returns a falsy value and in that case every returns false - otherwise it returns true

Example - some()

some also works very similar to every

  • some loops over the array elements left to right.

  • For each iteration, it calls the given function with the current array element as its 1st argument.

  • The loop continues, until the function returns a truthy value and in that case some returns true - otherwise it returns false

Now let's use some to test if some number in the array is odd,

nums.some(n => n % 2 == 1);

// true => 91 is odd

Clone this wiki locally