Control Structures: Conditionals and Loops
In JavaScript, there are several types of control structures for conditionals and loops.
Conditionals:
- If statement: The if statement in JavaScript is similar to other programming languages. It evaluates a condition and executes a block of code if the condition is true. Example:
if (x > 0) {
console.log("x is positive");
}
2. If-else statement: The if-else statement in JavaScript is also similar to other programming languages. It evaluates a condition and executes a block of code if the condition is true, otherwise it executes another block of code. Example:
if (x > 0) {
console.log("x is positive");
} else {
console.log("x is not positive");
}
3. Switch statement: The switch statement in JavaScript is used to select one of many code blocks to be executed. It evaluates an expression and compares it to multiple cases. If a case matches the expression, the corresponding block of code is executed. Example:
switch (color) {
case "red":
console.log("The color is red");
break;
case "blue":
console.log("The color is blue");
break;
default:
console.log("The color is not red or blue");
break;
}
Loops:
- While loop: The while loop in JavaScript executes a block of code as long as a specified condition is true. Example:
while (i < 5) {
console.log(i);
i++;
}
2. Do-while loop: The do-while loop in JavaScript is similar to the while loop, but it executes the block of code first, and then checks if the condition is true. Example:
do {
console.log(i);
i++;
} while (i < 5);
3. For loop: The for loop in JavaScript is used to loop through a block of code a specified number of times. Example:
for (var i = 0; i < 5; i++) {
console.log(i);
}