Thursday, 28 March, 2019 UTC


Summary

Javascript Array Every Example | Array.prototype.every() Tutorial is today’s topic. The every() method tests whether all items in an array pass the test implemented by the provided function. Javascript Array Every method executes the provided callback function once for each element present in the array until it finds one where returns a false value.
Javascript Array Every Example
The syntax of Javascript Array Every function is following.
array.every(function(currentValue, index, arr), thisValue)
The callback function is invoked with the three arguments: a value of the element, an index of the element, and the Array object being traversed.
currentValue: It is required, and it is the value of the current element.
index: It is an Optional. The array index of the current element.
arr: Optional. The array object the current element belongs to.
thisValue: Optional. A value to be passed to the function to be used as its “this” value. If this parameter is empty, the value “undefined” will be passed as its “this” value.
If a thisValue parameter is provided to every, it will be used as callback’s this value. Otherwise, the value undefined will be used as its this value.
See the following example.
// app.js

let arr = [1, 11, 21, 31, 41]

const diff = (currentValue) =>  currentValue < 51

console.log(arr.every(diff))
In the above example, the array contains the five elements.
Now, the javascript array every function takes one callback function. The callback function is a diff function, which takes currentValue of the array and checks the condition which is < 51.
If all the elements are under 51, then it returns true otherwise it will give us the false output. Here, also we have used the arrow function.
See the output below.
 
Let’s change one element of an array to 61 and test the output.
// app.js

let arr = [1, 11, 21, 31, 61]

const diff = (currentValue) =>  currentValue < 51

console.log(arr.every(diff))
So, here the last element of an array is higher than 51. So, the output will be false.
 
Finally, Javascript Array Every Example | Array.prototype.every() Tutorial is over.
The post Javascript Array Every Example | Array.prototype.every() Tutorial appeared first on AppDividend.