|
1 | 1 | # Loops |
2 | 2 |
|
3 | | -👨💼 Let's build a fun text banner using loops. We'll make a simple "staircase" |
4 | | -pattern of `*` characters. |
| 3 | +👨💼 Let's practice a simple `for` loop by building a numbered list. |
5 | 4 |
|
6 | | -🐨 Open <InlineFile file="index.ts" /> and: |
| 5 | +🐨 Open <InlineFile file="index.ts" /> and use a `for` loop to build a string |
| 6 | +with labels for exhibits 1 through 5. Each label should be on its own line. |
7 | 7 |
|
8 | | -1. Use a `for` loop to build 5 rows of stars |
9 | | -2. Each row should have one more `*` than the previous row |
10 | | -3. Put each row on its own line using `\n` |
11 | | - |
12 | | -💰 Traditional `for` loop structure: |
| 8 | +## How a `for` loop works |
13 | 9 |
|
14 | 10 | ```ts |
15 | | -for (let i = 0; i < count; i++) { |
16 | | - // do something |
| 11 | +for (let i = 0; i < limit; i++) { |
| 12 | + // repeat work |
17 | 13 | } |
18 | 14 | ``` |
19 | 15 |
|
20 | | -💰 String building with a loop: |
21 | | - |
22 | | -```ts |
23 | | -let output = '' |
24 | | -for (...) { |
25 | | - output += 'x' |
26 | | -} |
27 | | -``` |
| 16 | +Each part of the loop has a job: |
28 | 17 |
|
29 | | -💰 You'll need **two loops** for this exercise—an outer loop for each row, and |
30 | | -an inner loop to build the stars for that row. This is called a "nested loop": |
| 18 | +- **Initializer** (`let i = 0`) runs once before the loop starts |
| 19 | +- **Condition** (`i < limit`) is checked before each iteration |
| 20 | +- **Final expression** (`i++`) runs after each iteration |
31 | 21 |
|
32 | | -```ts |
33 | | -for (let row = 1; row <= 5; row++) { |
34 | | - // inner loop builds stars for this row |
35 | | - for (let star = 0; star < row; star++) { |
36 | | - // add a star |
37 | | - } |
38 | | -} |
39 | | -``` |
| 22 | +`i++` means "add 1 to `i`." It's the same as `i += 1`. |
40 | 23 |
|
41 | 24 | 📜 [MDN - for statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) |
42 | 25 |
|
|
0 commit comments