-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathfunctions.js
More file actions
57 lines (43 loc) · 1.75 KB
/
functions.js
File metadata and controls
57 lines (43 loc) · 1.75 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
// ==== Callbacks ====
/* Step 1: Create a higher-order function
* Create a higher-order function named consume with 3 parameters: a, b and cb
* The first two parameters can take any argument (we can pass any value as argument)
* The last parameter accepts a callback
* The consume function should return the invocation of cb, passing a and b into cb as arguments
*/
function consume(a,b,cb){
return cb(a,b)
}
/* Step 2: Create several functions to callback with consume();
* Create a function named add that returns the sum of two numbers
* Create a function named multiply that returns the product of two numbers
* Create a function named greeting that accepts a first and last name and returns "Hello first-name last-name, nice to meet you!"
*/
function add(a,b){
return a + b;
}
function multiply(a,b){
return a * b;
}
function greeting(firstName, lastName){
return `Hello ${firstName} ${lastName}, nice to meet you!`;
}
/* Step 3: Check your work by un-commenting the following calls to consume(): */
console.log(consume(2, 2, add)); // 4
console.log(consume(10, 16, multiply)); // 160
console.log(consume("Mary", "Poppins", greeting)); // Hello Mary Poppins, nice to meet you!
// ==== Closures ====
// Explain in your own words why nestedfunction can access the variable internal.
// Explanation:
// It begins by serching for the variable "internal" inside the nestedFunction's scope.
// since "internal" isn't there, JavaScript sees "nestedfunction" which is part of the outter function scope.
const external = "I'm outside the function";
function myFunction() {
console.log(external);
const internal = "Hello! I'm inside myFunction!";
function nestedFunction() {
console.log(internal);
};
nestedFunction();
}
myFunction();