26
Day 11 of #100DaysOfCode!
Today's progress
I learned about every()
and some()
methods.
What I learned
The every()
method tests whether every element in the array passes the test implemented by the provided function and returns a Boolean value
.
let numbers = [1, 2, 3, 4, 5]
const greaterThanZero = numbers.every(function(number){
return number > 0;
})
console.log(greaterThanZero)
//output: true
The above code example checks whether every
element in the array is greater than zero (number > 0). If so, it returns the boolean value true
.
The some()
method tests whether at least one element in the array passes the test implemented by the provided function and returns true
. Otherwise it returns false
. The original array is not modified.
let numbers = [100, 0, 2, 4, 10]
const isAnElementNegative = numbers.some(function(number){
return number < 0;
})
console.log(isAnElementNegative)
//output: false
The above code example outputs false because no element in the array is less than zero.
However, if we have an array with at least one negative element.
let numbers = [-5, 0, 2, 4, 10]
const isAnElementNegative = numbers.some(function(number){
return number < 0;
})
console.log(isAnElementNegative)
//output: true
Then the output will return true because at least one element is negative.
Filling in the gaps
Both every()
and some()
methods uses a callback function
on every element and returns a boolean value true
or false
.
The complete syntax for both methods is as follows:
every()
every(function(element, index, array))
some()
some(function(element, index, array))
For both methods the parameters index
and array
are optional.
Simply put
Both every()
and some()
methods are great tools when you want to derive a single boolean value from an array of elements.
Because they are standard JavaScript methods they can be much simple to read and use as compared to a forEach()
or reduce()
methods.
In other words, when solving a problem with arrays. Be sure to consider these tools in your toolkit as they can be powerful to help you find a solution.
26