|
| 1 | +## 07-The-World-of-Loops |
| 2 | + |
| 3 | +## 1. Intro to Loops |
| 4 | + |
| 5 | +### JS LOOPS Repeating Code |
| 6 | + |
| 7 | +### GOALS |
| 8 | + |
| 9 | +- Write for loops |
| 10 | +- Write while loops |
| 11 | +- Avoid infinite loops! |
| 12 | +- Iterate over arrays and objects |
| 13 | + |
| 14 | +### LOOPS |
| 15 | + |
| 16 | +Doing things repeatedly |
| 17 | + |
| 18 | +- Loops allow us to repeat code |
| 19 | + - "Print 'hello' 10 times |
| 20 | + - Sum all numbers in an array |
| 21 | +- There are multiple types: |
| 22 | + - for loop |
| 23 | + - while loop |
| 24 | + - for...of loop |
| 25 | + - for...in loop |
| 26 | + |
| 27 | +## 2. For Loops |
| 28 | + |
| 29 | +This is the syntax of a For Loop |
| 30 | + |
| 31 | +``` |
| 32 | +for ( |
| 33 | + [initialExpression]; // initial value |
| 34 | +
|
| 35 | + [condition]; // when to run the loop |
| 36 | +
|
| 37 | + [incrementExpression] // how to change value each time |
| 38 | +) |
| 39 | +``` |
| 40 | + |
| 41 | +``` |
| 42 | +for (let i = 200; i <= 0; i -= 25) { |
| 43 | + console.log('DOES IT WORK?'); |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +### ANOTHER EXAMPLE |
| 48 | + |
| 49 | +``` |
| 50 | +// Start at 50 |
| 51 | +// Stop at 0, Keep going as long as i>= 0 |
| 52 | +// Subtract 10 on each iteration |
| 53 | +for (let i = 50; i >= 0; i -= 10) { |
| 54 | + console.log(i); |
| 55 | + // 50, 40, 30, 20 ,10, 0 |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +## 3. Infinite Loops |
| 60 | + |
| 61 | +You can write infinite loops and an infinite loop is something you absolutely want to avoid. |
| 62 | + |
| 63 | +The idea behind the infinite loop is that you write a loop where the ending condition is never met. |
| 64 | + |
| 65 | +``` |
| 66 | +// DO NOT RUN THIS CODE! |
| 67 | +for (let i = 20; i >= 0; i++) { |
| 68 | + console.log(i); |
| 69 | +} // BAD!!! |
| 70 | +
|
| 71 | +// Or this infinite loop |
| 72 | +for(let i = 1; i !== 20; i+= 2) { |
| 73 | + console.log('Infinite Loop') |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +- Make sure you're going to the right direction |
| 78 | +- Your logic makes sense here |
| 79 | +- Generally try to avoid equality and non equality there |
| 80 | +- Prefer to use greater > than or < less than when i can |
0 commit comments