Javascript: control flow
By Dmitry Kabanov
Conditions
To execute some block of code depending on a condition, the following constructions are used; they are exactly like in C programming language.
Simple if
:
let x = 7;
if (x > 5) {
console.log("x is greater than five");
}
x is greater than five
Construction if
-else
:
x = 3;
if (x > 5) {
console.log("x is greater than five");
} else {
console.log("x is not greater than five");
}
x is not greater than five
And the conditions can be chained together:
if (x > 10) {
// Execute this if x > 10.
} else if (x > 5) {
// Execute this if x > 5 but x <= 10.
} else if (x > 3) {
// Execute this if x > 3 but x <= 3.
} else {
// Execute this if x <= 3.
}
While loop
While loop is the most fundamental type of loop used in programming languages:
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
For loop
Loops, where there is a counter variable that usually increments by one
on each iteration, are pretty common in programming. As other C-family
languages, Javascript offers for
loop for such situations:
for (let i = 0; i < 5; i++) {
let s = "";
for (let j = 0; j < i+1; j++) {
s += "*";
}
console.log(s);
}
*
**
***
****
*****
Note that there are two loops here—one is embedded in another. Moreover,
the variable j
of the inner loop is upper bounded by the variable i
of
the outer loop.