1function greeting(name) {
2 alert('Hello ' + name);
3}
4
5function processUserInput(callback) {
6 var name = prompt('Please enter your name.');
7 callback(name);
8}
9
10processUserInput(greeting);
1function greeting(name) {
2 alert('Hello ' + name);
3}
4
5function processUserInput(callback , {
6 var name = prompt('Please enter your name.');
7 callback(name);
8}}
9
10processUserInput(greeting);
1const add = (num1, num2) => num1 + num2;
2
3const result = (num1, num2, cb) => {
4 return "result is:" + cb(num1, num2);
5}
6
7const res = result(12, 13, add);
1// Callback Example 1: note, fn=function
2/*
3In JavaScript, callback fn is:
4
5- a function based into another functions as an argument to be
6 executed LATER
7- would be a Synchronous OR Asynchronous callback.
8- hint:
9
10 Synchronous: processing from top to bottom,
11 stop until current code finished.
12
13 Asynchronous: no wait, process the next block if there
14
15*/
16
17let numbers = [1, 2, 4, 7, 3, 5, 6];
18
19/* To find all the odd numbers in the array,
20you can use the filter() method of the Array object.
21- The filter() method creates a new array with the elements that
22pass the test implemented by a fn.
23- The following test fn returns true if a number is an odd
24number: */
25
26
27function isOddNumber(number) { //to be the callback fn
28 return number % 2;
29}
30
31// callback fn passed into another fn by its reference, No ()
32const oddNumbers = numbers.filter(isOddNumber);
33console.log(oddNumbers); // [ 1, 7, 3, 5 ]
34
1
2 function myDisplayer(some) { document.getElementById("demo").innerHTML
3 = some;}function myCalculator(num1, num2, myCallback) {
4 let sum = num1 + num2;
5 myCallback(sum);}myCalculator(5, 5, myDisplayer);
6