-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback-functions.js
79 lines (56 loc) · 1.81 KB
/
callback-functions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Global Execution Context
logger(2); // on global stack, logs (2,3,1) runs inside function first because it was called before function.
console.log(1)
function logger() {
console.log(2)
finish()
console.log(3)
function finish() {
console.log("finished")
}
}
logger(2); // runs after (1) in global stack logs (1,2,3)
// Function Execution Context
// What's a call back?
function message() {
console.log("hello there")
}
// this is a higher order function, which means a function that takes another function as a param
function logger1(message) {
message()
}
logger1(message)
// Other Examples of Callback Functions
// when you declare a function you can specify any argument that function can accept
function doSomething(value) {
console.log("convert txt to uppercase" + " " + value.toUpperCase())
}
doSomething("robert") // string argument
function doSomething1(value) {
console.log("math calcutation 10 * 20 = " + " " + value * 10)
}
doSomething1(20) // number
function doSomething2(value) {
console.log("callback with .length function =" + " " + value.length)
}
doSomething2([1,2,3,4,5]) // array
// Different types of values can be passed through a function and as well as a function passed as an argument.
// Pass the function as an arugment
// A callback function is a function that is passed as an argument to another function.
// Using a callback functions allows you to call a function from another function.
function doSomething3(value) {
value()
}
// passing function as argument
doSomething3(function() {
console.log("Sup G!")
})
// another example
function log(value) {
console.log(value) // just logs the value that is passed to it.
}
function calculateSum(num1, num2, print) {
const sum = num1 + num2
print(sum)
}
calculateSum(10,20, log)