-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-functions.js
More file actions
69 lines (46 loc) · 1.25 KB
/
01-functions.js
File metadata and controls
69 lines (46 loc) · 1.25 KB
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
// Different ways to declare a function in Javascript
// Traditional
function double_v1(n) {
return 2*n;
}
double_v1(5);
// Anonymous function assigned to a variable
const double_v2 = function (n) {
return 2*n;
}
double_v2(5);
// Anonymous function assigned to a variable, fat-arrow style
const double_v3 = n => 2*n;
double_v3(5);
// Anonymous function assigned to a variable, long fat-arrow style
const double_v4 = n => {
return 2*n;
}
double_v4(5);
// We can assign traditional functions to variables, too.
const double_v5 = double_v1;
double_v5(5);
// We can store (and call) functions in objects, and in arrays.
const obj = {
double(n) {
return 2*n;
}
}
obj.double(5);
const arr = [ n => 2*n ]
arr[0](5);
// An unadorned method name is a reference to the variable - it's only when we follow it
// with parentheses that it gets executed.
double_v1;
// And we can call methods on it.
double_v3.toString();
// We can pass functions as arguments to other functions.
const applier = (fn, num) => fn(num);
applier(double_v1, 5);
// Functions can return functions.
const createDoubler = () => {
return n => 2*n;
}
createDoubler()(5);
// Functions which take functions as arguments, or which return functions,
// are called Higher Order Functions.