-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJS Functions
More file actions
128 lines (91 loc) · 2.47 KB
/
JS Functions
File metadata and controls
128 lines (91 loc) · 2.47 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
function nameofFuction(parameter1, parameter2) {
//code to execute
}
//example
function saludar(nombre) {
console.log("Hola, " + nombre + "!");
}
//******"****
//1. CALLING A FUNCTION
function saludar(nombre) {
console.log("Hola, " + nombre + "!");
}
//Calls the function with "Juan" as an argument
saludar("Juan");
//************
//2. PARAMETERS AND ARGUMENTS
function addition(a, b) {
let resultado = a + b;
console.log("The addition is: " + resultado);
}
addition(5, 10); //The addition is: 15
//**************
//3. RETURN A VALUE
function multiply(a, b) {
return a * b;
}
let total = multiply(4, 5);
console.log("The total is: " + total); // The total is: 20
//**************
//4. ANONYMOUS FUNCTIONS
//Nameless functions that can be assigned to variables
let greet = function(name) {
return "Hi, " + name + "!";
};
console.log(greet("Ana")); //Hi, Ana!
//*************
//5. ARROW FUNCTIONS
//A shorter syntax to define anonymous functions
let nameOfFunction = (parameter1, parameter2) => {
//code to execute
};
//***************
// 6.FUNCTIONS AS FIRST CLASS OBJECTS
function operationMath(operation, a, b) {
return operation(a, b);
}
let sum = (x, y) => x + y;
let product = (x, y) => x * y;
console.log(operationMath(sum, 5, 3));
console.log(operationMath(product, 5, 3));
//*****************
//7. Superior Order Functions
//Functions which can receive other functions as arguments and return functions as results.
//This is possible since functions in Javascript are first class objects.
function applyOperation(operation, a, b) {
return operation(a, b);
}
function sum(x, y) {
return x + y;
}
function product(x, y) {
return x * y;
}
console.log(applyOperation(sum, 10, 20));
console.log(applyOperation(product, 10, 20));
//****************
//8. CLOSURES
//A function which remembers the lexical environment, the variables that were in the scope when the function was defined.
//This allows functions to access variables of its outside scope even after the context that they were created in was over.
function createCount() {
let counter = 0;
return function() {
counter++;
return counter;
};
}
let counter1 = createCount();
console.log(counter1());
console.log(counter1());
let counter2 = createCount();
console.log(counter2());
//************
//9. RECURSIVITY
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5));