javascript define callback function code example

Example 1: what are callback functions

// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
funct printANumber(int number, funct callbackFunction) {
    printout("The number you provided is: " + number);
}

// a function which we will use in a driver function as a callback function
funct printFinishMessage() {
    printout("I have finished printing numbers.");
}

// Driver method
funct event() {
   printANumber(6, printFinishMessage);
}

Example 2: javascript callback function

// Callback Example 1: note, fn=function
/* 
In JavaScript, callback fn is:

- a function based into another functions as an argument to be
	executed LATER
- would be a Synchronous OR Asynchronous callback.
- hint: 

	Synchronous: processing from top to bottom, 
	stop until current code finished.
        
	Asynchronous: no wait, process the next block if there
    
*/

let numbers = [1, 2, 4, 7, 3, 5, 6];

/* To find all the odd numbers in the array, 
you can use the filter() method of the Array object.
- The filter() method creates a new array with the elements that
pass the test implemented by a fn.
- The following test fn returns true if a number is an odd
number:   */


function isOddNumber(number) { //to be the callback fn
    return number % 2;
}

// callback fn passed into another fn by its reference, No ()
const oddNumbers = numbers.filter(isOddNumber);
console.log(oddNumbers); // [ 1, 7, 3, 5 ]