GeezerVison is showing github.com — Add article about for loop · eazel7/javascript@7836866
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +47Lines changed: 47 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +# For Loop |
| 2 | + |
| 3 | +The easiest form of a loop is the for statement. This one has a syntax that is similar to an if statement, but with more options: |
| 4 | + |
| 5 | +``` |
| 6 | +for(condition; end condition; change){ |
| 7 | + // do it, do it now |
| 8 | +} |
| 9 | +``` |
| 10 | + |
| 11 | +Lets for example see how to execute the same code ten-times using a `for` loop: |
| 12 | + |
| 13 | +``` |
| 14 | +for(var i = 0; i < 10; i = i + 1){ |
| 15 | + // do this code ten-times |
| 16 | +} |
| 17 | +``` |
| 18 | + |
| 19 | +**Note**: `i = i + 1` can be written `i++`. |
| 20 | + |
| 21 | + |
| 22 | +--- |
| 23 | + |
| 24 | +Create using a for-loop a variable named `message` which equals the concatenation of integers (1, 2, 3, ...) from 0 to 100. |
| 25 | + |
| 26 | +```js |
| 27 | +var message = "" |
| 28 | +``` |
| 29 | + |
| 30 | +```js |
| 31 | +var message = "" |
| 32 | + |
| 33 | +for(var i = 0; i < 100; i++){ |
| 34 | + message = message + i; |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +```js |
| 39 | +var message2 = "" |
| 40 | + |
| 41 | +for(var i = 0; i < 100; i++){ |
| 42 | + message2 = message2 + i; |
| 43 | +} |
| 44 | +assert(message == message2); |
| 45 | +``` |
| 46 | + |
| 47 | +--- |