JavaScript Arrays: Some(), Every(), and forEach()

Explaining the uses for each method

The Some() Method

The some() method iterates through elements and checks if any value in the array satisfies a condition. The some() method accepts a boolean expression with the following signature:

(element) => boolean

The element is the current element in the array whose value is being checked.

The boolean denotes that the function returns a boolean value.

Consider the following array of integers:

let arr = [1, 2, 3, 4, 5, 6, 7, 8];

We will be using the some() method to check if at least one element is in the array.

arr.some((value)=> { return (value%2 == 0); });

Output:

true

The array contains elements divisible by 2, so the some() method returned true.

When you use the some() method to find negative numbers:

arr.some((value)=> { return (value < 0); });

The output is:

false

It is false because there are no numbers in the array that are negative.

The some() method stops iterating as soon as the element is found, which satisfies the required boolean expression.

arr.some((value) => { 
index++;
console.log(index);
return (value % 2 == 0);
});

Output is:

1 2 true

The Every() Method

As opposed to some(), the every() method checks whether the elements in the array satisfy the boolean expression. If even a single value doesn't satisfy the element it returns false, otherwise it returns true.

let arr = [1, 2, 3, 4, 5, 6, 7, 8];arr.every((value)=> { 
return (value > 0);
});

As all of the values in the array arr are positive, the boolean expression satisfies for all of the values. We receive true as output.

If there is a single value that doesn’t satisfy the boolean expression, we get the boolean output false.

arr.every((value)=> { return (value == 5); });

Output:

false

The every() method stops iterating over the elements as soon as any value fails the boolean expression.

arr.every((value) => { 
index++;
console.log(index);
return (value != 4);
});

Output:

1 2 3 false

The forEach() method

The forEach() method, as the name suggests, is used to iterate over every element of the array and perform a desired operation with it.

let arr = [1, 2, 3, 4, 5, 6, 7, 8];arr.forEach((value) => { 
console.log(value == 5);
});

We get the output as:

false false false false true false false false

Nothing different here, just iterating each element with an operation (as required) on it.