Web development and Tech news Blog site. WEBISFREE.com

HOME > js

Learning about the JavaScript array method every()

Last Modified : 03 Mar, 2023 / Created : 03 Mar, 2023
View Count
Let's learn about the every() method used in arrays in JavaScript.

# JavaScript Array Method every()

The every() method was added in ES 5 and is supported by most browsers. It is used in arrays to verify all the values ​​it contains, and it can return the result as a boolean value of true/false. For example, you can check if the values ​​in an array are larger or smaller than a particular value, or if they are even or odd. So, let's take a look at the syntax of this straightforward method.

Array.every(function, this[option])

The simple grammar as shown above receives functions and this values as arguments. For required functions, the following values are used.
function(currentValue, index, array) {

* Arguments used in the function:
  • currentValue [Required] // The current value of the array at this index.
  • index [Optional] // The current index value.

As shown above, all values except the current value are optional and not mandatory. If needed, the "this" value can be specified.

As mentioned before, the "every()" method checks if all values in an array meet a condition and returns a boolean value. Therefore, the function requires a condition that always returns a value.
function() {
  return condition

! See the example of the every() function in JavaScript.

Let's make a simple example to understand. The following two examples are each using every() to verify a specific condition of the values in an array.

Example 1) Determining if a certain number is greater or smaller
To find out if a value is greater or not than a certain number, a variable named "test" was created and executed as shown below, and the results are as follows.
test = [1, 2, 3]
test.every((i) => { return i > 0; })
test.every((i) => { return i > -1; })

// Result
Every returns true

The above examples all satisfy the condition because they are larger than 0 and -1. Therefore, they return true. If the following cases do not meet the condition, they return false.
test.every((i) => { return i > 1; })
test.every((i) => { return i > 2; })
test.every((i) => { return i > 3; })

// Result
Every returns false

Example 2) Checking if there are negative values in an array
For this example, we wrote code to check if there are negative values included. If a value is less than 0, we can assume that it has a negative value.
test = [1 , 0, 10, -2]
test.every((i) => { return i < 0; })

// Result

The result returns true because the array test contains a negative number of -2.

So far, we have briefly learned about the built-in function and method of the array, every().


How to get the name of a JavaScript function?


How to smoothly scroll to a specific element