1/*
2A callback function is a function passed into another function
3as an argument, which is then invoked inside the outer function
4to complete some kind of routine or action.
5*/
6function greeting(name) {
7 alert('Hello ' + name);
8}
9
10function processUserInput(callback) {
11 var name = prompt('Please enter your name.');
12 callback(name);
13}
14
15processUserInput(greeting);
16// The above example is a synchronous callback, as it is executed immediately.
1function startWith(message, callback){
2 console.log("Clearly written messages is: " + message);
3
4 //check if the callback variable is a function..
5 if(typeof callback == "function"){
6 callback(); //execute function if function is truly a function.
7 }
8}
9//finally execute function at the end
10startWith("This Messsage", function mySpecialCallback(){
11 console.log("Message from callback function");
12})
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 add(a, b, callback) {
2 if (callback && typeof(callback) === "function") {
3 callback(a + b);
4 }
5}
6
7add(5, 3, function(answer) {
8 console.log(answer);
9});
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
1const message = function() {
2 console.log("This message is shown after 3 seconds");
3}
4
5setTimeout(message, 3000);