GeezerVison is showing github.com — Add article about while loop · CSR-24/javascript@ac6fe15
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 clipboardExpand all lines: loops/for.md +1-1Lines changed: 1 addition & 1 deletion - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
|
2 | 2 |
|
3 | 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 | 4 |
|
5 | | -``` |
| 5 | +```javascript |
6 | 6 | for(condition; end condition; change){ |
7 | 7 | // do it, do it now |
8 | 8 | } |
|
Collapse file
Copy file name to clipboard +62Lines changed: 62 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +# While Loop |
| 2 | + |
| 3 | +While Loops can execute a block of code as long as a specified condition is true. |
| 4 | + |
| 5 | +```javascript |
| 6 | +while(condition){ |
| 7 | + // do it as long as condition is true |
| 8 | +} |
| 9 | +``` |
| 10 | + |
| 11 | +For example, The loop in this example will continue to run as long as the variable i is less than 5: |
| 12 | + |
| 13 | +```javascript |
| 14 | +var i = 0, x = ""; |
| 15 | +while (i < 5) { |
| 16 | + x = x + "The number is " + i; |
| 17 | + i++; |
| 18 | +} |
| 19 | +``` |
| 20 | + |
| 21 | +The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true: |
| 22 | + |
| 23 | +```javascript |
| 24 | +do { |
| 25 | + // code block to be executed |
| 26 | +} while (condition); |
| 27 | +``` |
| 28 | + |
| 29 | + |
| 30 | +**Note**: Be careful to avoid infinite looping if the condition is always true! |
| 31 | + |
| 32 | + |
| 33 | +--- |
| 34 | + |
| 35 | +Create using a while-loop a variable named `message` which equals the concatenation of integers (1, 2, 3, ...) as long as its length (`message.length`) is inferior to 100. |
| 36 | + |
| 37 | +```js |
| 38 | +var message = ""; |
| 39 | +``` |
| 40 | + |
| 41 | +```js |
| 42 | +var message = ""; |
| 43 | +var i = 0; |
| 44 | + |
| 45 | +while (message.length < 100) { |
| 46 | + message = message + i; |
| 47 | + i = i + 1; |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +```js |
| 52 | +var message2 = ""; |
| 53 | +var i2 = 0; |
| 54 | + |
| 55 | +while (message2.length < 100) { |
| 56 | + message2 = message2 + i2; |
| 57 | + i2 = i2 + 1; |
| 58 | +} |
| 59 | +assert(message == message2); |
| 60 | +``` |
| 61 | + |
| 62 | +--- |