-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path15-general-loops.js
137 lines (117 loc) · 2.11 KB
/
15-general-loops.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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/**
* ******************************
* General Loops
* ******************************
**/
/**
* ********************
* FOR LOOP
* ********************
**/
for (let i = 0; i < 10; i++) {
console.log(i);
}
/**
* ********************
* SKIP ITERATION (CONTINUE KEYWORD)
* ********************
**/
for (let i = 0; i < 10; i++) {
if (i === 2) {
console.log('2 is my favourite number');
continue;
}
console.log('Number ' + i);
}
/**
* ********************
* BREAK OUT OF LOOP (BREAK KEYWORD)
* ********************
**/
for (let i = 0; i < 10; i++) {
if (i === 5) {
console.log('Stop the loop');
break;
}
console.log('Number ' + i);
}
/**
* ********************
* WHILE LOOP
* ********************
**/
let i = 0;
while (i < 5) {
console.log('Number ' + i);
i++;
}
/**
* ********************
* DO WHILE
* ********************
**/
let i = 100;
do {
console.log('Number ' + i);
i++;
} while (i < 10);
/**
* ********************
* LOOP THROUGH ARRAY
* ********************
**/
const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
// for loops with Arrays
for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}
// while loops with Arrays
let i = 0;
while (i < cars.length) {
console.log(cars[i]);
i++;
}
/**
* ********************
* ARRAY LOOP: FOREACH
* ********************
**/
// Function with one parameter
cars.forEach(function(car) {
console.log(car);
});
// Function with three parameters (2 parameters are optional)
cars.forEach(function(car, index, array) {
console.log(`${index}: ${car}`);
console.log(array);
});
/**
* ********************
* ARRAY LOOP: MAP
* ********************
**/
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Sara' },
{ id: 3, name: 'Karen' },
{ id: 4, name: 'Steve' }
];
const newUser = users.map(function(user) {
return `${user.id}: ${user.id}`;
});
/**
* ********************
* FOR IN LOOP
* ********************
**/
const user = {
firstName: 'John',
lastName: 'Doe',
age: 40
};
for (let prop in user) {
console.log(prop);
}
for (let prop in user) {
console.log(`${prop}: ${user[prop]}`);
}