-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path018-loops.js
More file actions
67 lines (54 loc) · 1.4 KB
/
018-loops.js
File metadata and controls
67 lines (54 loc) · 1.4 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
// WHAT ARE LOOPS?
// console.log("Iteration 1");
// console.log("Iteration 2");
// console.log("Iteration 3");
// console.log("Iteration 4");
// console.log("Iteration 5");
// for (let i = 1; i <= 5; i++) {
// console.log("Iteration " + i);
// }
// WHY DO WE NEED LOOPS?
// 1. Processing Collections of Data
// 2. Repeating Actions
// 3. Performing Calculations
// 4. Game Development
// 5. User Interfaces
// TYPES OF LOOPS IN JAVASCRIPT
// 1. For Loop
// 2. While Loop
// 3. Do-While Loop
// 4. Nested Loops
// LOOP ANATOMY - BASIC STRUCTURE
// 1. Initialization
// 2. Condition
// 3. Update/Increment
// for (initialization; condition; update) {
// // code to be executed
// }
// for (let i = 0; i < 5; i++) {
// console.log(i);
// }
// A QUICK TEASER EXAMPLE
// Without a loop
// let sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
// console.log(sum); // 55
// With a loop:
// let sum = 0;
// for (let i = 1; i <= 1000; i++) {
// sum += i;
// }
// console.log(sum); // 55
// for (let i = 1; i <= 5; i++) {
// console.log("*".repeat(i));
// }
// COMMON MISTAKES
// 1. Infinite Loops
// BAD - Infinite loop!
for (let i = 0; i < 10; ) {
console.log(i);
// i never increases!
}
// 2. Off-by-One Errors
// < vs <=
// BEST PRACTICES
// CONCLUSION