0% found this document useful (0 votes)
11 views6 pages

Lecture JS - Callback Function

The document explains the concept of callback functions, which are functions passed as arguments to other functions and invoked within them. It provides examples of using a callback function in a 'greet' function and demonstrates array traversal using 'for' loops and 'forEach' methods with a custom 'myEvery' function. The 'myEvery' function checks if all elements in an array satisfy a given condition defined by the callback function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Lecture JS - Callback Function

The document explains the concept of callback functions, which are functions passed as arguments to other functions and invoked within them. It provides examples of using a callback function in a 'greet' function and demonstrates array traversal using 'for' loops and 'forEach' methods with a custom 'myEvery' function. The 'myEvery' function checks if all elements in an array satisfy a given condition defined by the callback function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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.

You might also like