Get to know exact situations where we can use and where not.
every() returns true if all elements in an array pass a test function, while find() returns the first element in an array that passes a test function. below example
const surveyors = [{
name: "Steve",
answer: "Yes"
},
{
name: "Jessica",
answer: "Yes"
},
{
name: "Peter",
answer: "Yes"
},
{
name: "Elaine",
answer: "No"
}
];
surveyors.find((value, index) => {
if (value.answer === "Yes") {
console.log(value);
}
});
// output
/* {
answer: "Yes",
name: "Steve"
}
{
answer: "Yes",
name: "Jessica"
}
{
answer: "Yes",
name: "Peter"
} */
surveyors.every((value, index) => {
if (value.answer === "Yes") {
console.log(value);
}
});
// output
/* {
answer: "Yes",
name: "Steve"
} */
3
Answers
You’re not returning anything in either examples. In javascript, not returning anything is equivalent to returning
undefined
.Also in javascript,
undefined
is falsy. That is, if coerced to a boolean it is equivalent tofalse
.Since
.every()
tests if all elements in the array returnstrue
then it does not need to check any other element if the first one returnsfalse
.every
method is an iterative method.It calls a callback function for each element in an array, until the callback function returns a falsy value. If such an element is found,every()
immediately returns false and stops iterating through the array. In your case since you are not explicitly returning anything soundefined
will be returned which will be considered asfalsy
and the callback function will stop executing.That is the reason it is not logging further values
It can be helpful to understand the purposes of the callback functions passed to these two methods.
For
find
: "It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise." See here. The callback function will run until it encounters a "truthy" return value. In your case, the callback function infind
is actually running on every item in the array, because the callback function never returns a "truthy" value (it’s returningundefined
every time). The log to the console only runs 3 times, because those are the times it passes your conditional.For
every
: "It should return a truthy value to indicate the element passes the test, and a falsy value otherwise." See here. The callback function will run on every item until it encounters a "falsy" return value; if it makes it to the end without hitting a "falsy" value, it knows the overall answer isTrue
. In your case, the callback function forevery
is only running once, because the when it hits the first item and sees thatundefined
(a "falsey" value) is returned, it knows it doesn’t have to go any further — if even one item is falsey, the return value for the whole method isfalse
. Because of that, it is able to short-circuit and stop.