Callback function
A callback function is a function that is passed as an argument to another function, and is
usually called (invoked) inside that function to complete some kind of routine or action.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Alice", sayBye);
Use for loop for array traversing
function myEvery(array, callback) {
for (let i = 0; i < array.length; i++) {
if (!callback(array[i])) {
return false;
}
}
return true;
}
// Example usage:
var a = [1, 2, 3, 4];
var result = myEvery(a, x => x > 0);
console.log(result); // Output: true
Use forEach for array traversing
function myEvery(arr, callback) {
var res=true;
arr.forEach(x=>{
if(!callback(x)){
res= false;
} });
return res;
}
// Example usage:
var a = [1, -2, 3, 4];
var result = myEvery(a, x => x > 0);
console.log(result); // Output: true
Explanation:
array: the array you want to check.
callback: the function that tests each element.
If the callback returns false for any element, myEvery returns false.
If the callback returns true for all elements, it returns true.