Skip to content

Commit ac6fe15

Browse files
committed
Add article about while loop
1 parent cd41598 commit ac6fe15

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

loops/for.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
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:
44

5-
```
5+
```javascript
66
for(condition; end condition; change){
77
// do it, do it now
88
}

loops/while.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
---

0 commit comments

Comments
 (0)