Skip to main content

Command Palette

Search for a command to run...

some() and every() method in Java Script

Published
2 min readView as Markdown
some() and every() method in Java Script

1. some():-

This is an inbuilt method of JavaScript.

  • If at least one element in the array implements the logic then only this method will return a true Boolean value as output.
  • If not a single element of the existing array is able the satisfied the logic then only this method will return the false Boolean value as output.

    It doesn't modify the array.

Parameters

callback function :- A function to test for each element.

The function is called with the following arguments:

  • element:- The current element being processed in the array.
1. Check whether at least one element is even or not. if yes return true else return false.
let arr = [2, 5, 10, 7, 9]
let result = arr.some((element)=>
    element%2 == 0
)
console.log(result) - true
2. Check whether at least one element is even or not. if yes return true else return false.
let arr = [3, 5, 11, 7, 9]
let result = arr.some((element)=>
    element%2 == 0
)
console.log(result) - false

2. every():-

This is also an inbuilt method of JavaScript.

  • every() method of JavaScript goes inside the array and checks each element of the array.

  • If all the elements in an array implement the logic then only, this method will return true Boolean value as output.

  • If at least one element of an array is not able to impendent the logic, this method will return a ' false ' Boolean value as output.

Parameters

callback function :- A function to test for each element.

The function is called with the following arguments:

  • element:- The current element being processed in the array.

element is a variable and variable name can be anything.

 Check whether all elements of the array are even or not. if yes return true else return false.
(i) let arr = [2, 4, 6, 8, 12]
let result = arr.every((element)=>
    element%2 == 0
)
console.log(result) - true

(ii) let arr = [2, 4, 3, 8, 12]
let result = arr.every((value)=>
    value%2 == 0
)
console.log(result) - false

Note:- some() and every() method of JavaScript will not modify the origin array.