I’m not sure how to check every element to the callback and check if they are all true; I am also quite new to trying to code so sorry if it looks bad.
Write a function myEvery
that accepts an array and a callback as arguments.
The function should return a boolean indicating whether or not all elements of
the array return true when passed into the callback.
Do not use the built in Array#every
let myEvery = function(arr, cb) {
let bool = false;
if (cb(arr) === true) {
bool = true;
}
return bool;
};
2
Answers
@Kooilnc’s response for ‘[].every()’ should be used in such cases, but as for an understanding about creating callbacks & functions that use callbacks, or validation functions within conditionals, I’ll write a little something that helped me understand them better.
& this question is not really a callback context, but just a use of functions in a ‘first-class’ manner. Callbacks, to me, seemed to be designed and named for their ability to call a function/method when their execution context has completed, but def not limited to only this.
To give an example of callbacks, and checking the values returned by the "callback" or "higher-order function" see below for an amateur example.
p.s. I am not a professional, just a hobbyist who likes to learn!
Every time the runtime (or compiler depending on the language/context) approaches a function call within another function, the js runtime will pause the execution of the current function stack, create a new execution stack and run the new one until completes or returns a value, after which it resumes the previous execution context, etc.
You could use
for..
to loop through the array and return false immediately if the callback returns falsy value. Not that checking whether all array items aretrue
should be done in the callback not inmyEvery
. All array filter/check methods work with truthy/false values returned from callbacks. Learn here:https://developer.mozilla.org/en-US/docs/Glossary/Falsy
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
Also note that for checking whether array items truthy/false you could use
Boolean()
which is a constructor of a wrapper object of a boolean primitive which is used then as a true/false condition.Here’s a log of what happens: