You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/12-while-for/article.md
+44-46Lines changed: 44 additions & 46 deletions
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,10 @@
1
1
# Loops: while and for
2
2
3
-
We often have a need to perform similar actions many times in a row.
3
+
We often need to repeat actions.
4
4
5
-
For example, when we need to output goods from a list one after another. Or just run the same code for each number from 1 to 10.
5
+
For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10.
6
6
7
-
*Loops* are a way to repeat the same part of code multiple times.
7
+
*Loops* are a way to repeat the same code multiple times.
8
8
9
9
## The "while" loop
10
10
@@ -31,11 +31,11 @@ while (i < 3) { // shows 0, then 1, then 2
31
31
32
32
A single execution of the loop body is called *an iteration*. The loop in the example above makes three iterations.
33
33
34
-
If there were no `i++` in the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and for server-side JavaScript we can kill the process.
34
+
If there were no `i++` in the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops and in server-side JavaScript, we can kill the process.
35
35
36
-
Any expression or a variable can be a loop condition, not just a comparison. They are evaluated and converted to a boolean by `while`.
36
+
Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by `while`.
37
37
38
-
For instance, the shorter way to write `while (i != 0)`could be`while (i)`:
38
+
For instance, a shorter way to write `while (i != 0)`is`while (i)`:
39
39
40
40
```js run
41
41
let i =3;
@@ -68,7 +68,7 @@ do {
68
68
} while (condition);
69
69
```
70
70
71
-
The loop will first execute the body, then check the condition and, while it's truthy, execute it again and again.
71
+
The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again.
72
72
73
73
For example:
74
74
@@ -80,11 +80,11 @@ do {
80
80
} while (i <3);
81
81
```
82
82
83
-
This form of syntax is rarely used except when you want the body of the loop to execute **at least once** regardless of the condition being truthy. Usually, the other form is preferred: `while(…) {…}`.
83
+
This form of syntax should only be used when you want the body of the loop to execute **at least once** regardless of the condition being truthy. Usually, the other form is preferred: `while(…) {…}`.
84
84
85
85
## The "for" loop
86
86
87
-
The `for` loop is the most often used one.
87
+
The `for` loop is the most commonly used loop.
88
88
89
89
It looks like this:
90
90
@@ -102,14 +102,14 @@ for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
| begin |`i = 0`| Executes once upon entering the loop. |
110
-
| condition |`i < 3`| Checked before every loop iteration, if fails the loop stops. |
111
-
| step|`i++`| Executes after the body on each iteration, but before the condition check. |
112
-
| body |`alert(i)`| Runs again and again while the condition is truthy |
110
+
| condition |`i < 3`| Checked before every loop iteration. If false, the loop stops. |
111
+
| step|`i++`| Executes after the body on each iteration but before the condition check. |
112
+
| body |`alert(i)`| Runs again and again while the condition is truthy.|
113
113
114
114
115
115
The general loop algorithm works like this:
@@ -121,9 +121,9 @@ Run begin
121
121
→ ...
122
122
```
123
123
124
-
If you are new to loops, then maybe it would help if you go back to the example and reproduce how it runs step-by-step on a piece of paper.
124
+
If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper.
125
125
126
-
Here's what exactly happens in our case:
126
+
Here's exactly what happens in our case:
127
127
128
128
```js
129
129
// for (let i = 0; i < 3; i++) alert(i)
@@ -140,7 +140,7 @@ if (i < 3) { alert(i); i++ }
140
140
```
141
141
142
142
````smart header="Inline variable declaration"
143
-
Here the "counter" variable `i` is declared right in the loop. That's called an "inline" variable declaration. Such variables are visible only inside the loop.
143
+
Here, the "counter" variable `i` is declared right in the loop. This is called an "inline" variable declaration. Such variables are visible only inside the loop.
144
144
145
145
```js run
146
146
for (*!*let*/!* i = 0; i < 3; i++) {
@@ -149,7 +149,7 @@ for (*!*let*/!* i = 0; i < 3; i++) {
149
149
alert(i); // error, no such variable
150
150
```
151
151
152
-
Instead of defining a variable, we can use an existing one:
152
+
Instead of defining a variable, we could use an existing one:
153
153
154
154
```js run
155
155
let i = 0;
@@ -166,7 +166,7 @@ alert(i); // 3, visible, because declared outside of the loop
166
166
167
167
### Skipping parts
168
168
169
-
Any part of `for` can be skipped.
169
+
Any part of the `for` syntax can be skipped.
170
170
171
171
For example, we can omit `begin` if we don't need to do anything at the loop start.
172
172
@@ -200,15 +200,15 @@ for (;;) {
200
200
}
201
201
```
202
202
203
-
Please note that the two `for` semicolons `;` must be present, otherwise it would be a syntax error.
203
+
Please note that the two `for` semicolons `;` must be present. Otherwise, there would be a syntax error.
204
204
205
205
## Breaking the loop
206
206
207
-
Normally the loop exits when the condition becomes falsy.
207
+
Normally, a loop exits when its condition becomes falsy.
208
208
209
-
But we can force the exit at any moment. There's a special `break` directive for that.
209
+
But we can force the exit at any time using the special `break` directive.
210
210
211
-
For example, the loop below asks the user for a series of numbers, but "breaks" when no number is entered:
211
+
For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered:
212
212
213
213
```js
214
214
let sum =0;
@@ -227,15 +227,15 @@ while (true) {
227
227
alert( 'Sum: '+ sum );
228
228
```
229
229
230
-
The `break` directive is activated at the line `(*)` if the user enters an empty line or cancels the input. It stops the loop immediately, passing the control to the first line after the loop. Namely, `alert`.
230
+
The `break` directive is activated at the line `(*)` if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, `alert`.
231
231
232
-
The combination "infinite loop + `break` as needed" is great for situations when the condition must be checked not in the beginning/end of the loop, but in the middle, or even in several places of the body.
232
+
The combination "infinite loop + `break` as needed" is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of the body.
233
233
234
234
## Continue to the next iteration [#continue]
235
235
236
-
The `continue` directive is a "lighter version" of `break`. It doesn't stop the whole loop. Instead it stops the current iteration and forces the loop to start a new one (if the condition allows).
236
+
The `continue` directive is a "lighter version" of `break`. It doesn't stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
237
237
238
-
We can use it if we're done on the current iteration and would like to move on to the next.
238
+
We can use it if we're done with the current iteration and would like to move on to the next one.
239
239
240
240
The loop below uses `continue` to output only odd values:
241
241
@@ -249,9 +249,9 @@ for (let i = 0; i < 10; i++) {
249
249
}
250
250
```
251
251
252
-
For even values of `i` the `continue` directive stops body execution, passing the control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values.
252
+
For even values of `i`, the `continue` directive stops executing the body and passes control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values.
253
253
254
-
````smart header="The directive `continue` helps to decrease nesting level"
A loop that shows odd values could look like this:
256
256
257
257
```js
@@ -264,13 +264,13 @@ for (let i = 0; i < 10; i++) {
264
264
}
265
265
```
266
266
267
-
From a technical point of view it's identical to the example above. Surely, we can just wrap the code in the`if` block instead of `continue`.
267
+
From a technical point of view, this is identical to the example above. Surely, we can just wrap the code in an`if` block instead of using`continue`.
268
268
269
-
But as a side-effect we got one more nesting level (the `alert` call inside the curly braces). If the code inside `if` is longer than a few lines, that may decrease the overall readability.
269
+
But as a side-effect, this created one more level of nesting (the `alert` call inside the curly braces). If the code inside of`if` is longer than a few lines, that may decrease the overall readability.
270
270
````
271
271
272
272
````warn header="No `break/continue` to the right side of '?'"
273
-
Please note that syntax constructs that are not expressions cannot be used with the ternary operator `?`. In particular, directives such as `break/continue` are disallowed there.
273
+
Please note that syntax constructs that are not expressions cannot be used with the ternary operator `?`. In particular, directives such as `break/continue` aren't allowed there.
274
274
275
275
For example, if we take this code:
276
276
@@ -282,24 +282,24 @@ if (i > 5) {
282
282
}
283
283
```
284
284
285
-
...And rewrite it using a question mark:
285
+
...and rewrite it using a question mark:
286
286
287
287
288
288
```js no-beautify
289
-
(i > 5) ? alert(i) : *!*continue*/!*; // continue not allowed here
289
+
(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here
290
290
```
291
291
292
-
...Then it stops working. The code like this will give a syntax error:
292
+
...it stops working. Code like this will give a syntax error:
293
293
294
294
295
-
That's just another reason not to use a question mark operator `?` instead of `if`.
295
+
This is just another reason not to use the question mark operator `?` instead of `if`.
296
296
````
297
297
298
298
## Labels for break/continue
299
299
300
300
Sometimes we need to break out from multiple nested loops at once.
301
301
302
-
For example, in the code below we loop over `i` and `j` prompting for coordinates `(i, j)` from `(0,0)` to `(3,3)`:
302
+
For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(3,3)`:
303
303
304
304
```js run no-beautify
305
305
for (let i =0; i <3; i++) {
@@ -318,7 +318,7 @@ alert('Done!');
318
318
319
319
We need a way to stop the process if the user cancels the input.
320
320
321
-
The ordinary `break` after `input` would only break the inner loop. That's not sufficient. Labels come to the rescue.
321
+
The ordinary `break` after `input` would only break the inner loop. That's not sufficient--labels, come to the rescue!
322
322
323
323
A *label* is an identifier with a colon before a loop:
324
324
```js
@@ -327,9 +327,7 @@ labelName: for (...) {
327
327
}
328
328
```
329
329
330
-
The `break <labelName>` statement in the loop breaks out to the label.
331
-
332
-
Like here:
330
+
The `break <labelName>` statement in the loop below breaks out to the label:
333
331
334
332
```js run no-beautify
335
333
*!*outer:*/!*for (let i =0; i <3; i++) {
@@ -347,7 +345,7 @@ Like here:
347
345
alert('Done!');
348
346
```
349
347
350
-
In the code above `break outer` looks upwards for the label named `outer` and breaks out of that loop.
348
+
In the code above,`break outer` looks upwards for the label named `outer` and breaks out of that loop.
351
349
352
350
So the control goes straight from `(*)` to `alert('Done!')`.
353
351
@@ -358,10 +356,10 @@ outer:
358
356
for (let i =0; i <3; i++) { ... }
359
357
```
360
358
361
-
The `continue` directive can also be used with a label. In this case the execution jumps to the next iteration of the labeled loop.
359
+
The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop.
362
360
363
361
````warn header="Labels are not a \"goto\""
364
-
Labels do not allow us to jump into an arbitrary place of code.
362
+
Labels do not allow us to jump into an arbitrary place in the code.
0 commit comments