Control Flow
In JavaScript, control flow allows us to control the order in which statements are executed based on certain conditions. This is useful when we want to perform different actions depending on whether a condition is true or false.
Conditional Statements
Conditional statements in JavaScript allow us to execute different blocks of code depending on whether a condition is true or false. The most common conditional statement is the if
statement.
Here's an example of using an if
statement to check if a number is divisible by 3 and 5 and print 'FizzBuzz':
JAVASCRIPT
1// replace with ts logic relevant to content (make sure to log something)
2for (let i = 1; i <= 100; i++) {
3 if (i % 3 === 0 && i % 5 === 0) {
4 console.log("FizzBuzz");
5 } else if (i % 3 === 0) {
6 console.log("Fizz");
7 } else if (i % 5 === 0) {
8 console.log("Buzz");
9 } else {
10 console.log(i);
11 }
12}
Output:
SNIPPET
11
22
3Fizz
44
5Buzz
6Fizz
77
88
9Fizz
10...
xxxxxxxxxx
11
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment