Day 11 of #100DaysOfCode!

cfalucho

Christian Falucho

Posted on June 30, 2021

Day 11 of #100DaysOfCode!

Today's progress

I learned about every() and some() methods.

What I learned

every() method

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
Enter fullscreen mode Exit fullscreen mode

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.

some() method

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

some()

some(function(element, index, array))
Enter fullscreen mode Exit fullscreen mode

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
cfalucho
Christian Falucho

Posted on June 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 12 of #100DaysOfCode!
javascript Day 12 of #100DaysOfCode!

July 6, 2021

Day 8 of #100DaysOfCode!
javascript Day 8 of #100DaysOfCode!

June 24, 2021

Day 6 of #100DaysOfCode!
javascript Day 6 of #100DaysOfCode!

June 22, 2021

Day 11 of #100DaysOfCode!
javascript Day 11 of #100DaysOfCode!

June 30, 2021

Day 7 of #100DaysOfCode!
javascript Day 7 of #100DaysOfCode!

June 22, 2021