Conditional statements allow the program to make decisions based on whether a condition is true or false.
The if statement tests a condition and executes the block of code if the condition is true.
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
The else statement provides an alternative block of code that will execute when the condition is false.
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
The else if statement allows for multiple conditions to be tested in sequence.
let timeOfDay = 14;
if (timeOfDay < 12) {
console.log("Good morning!");
} else if (timeOfDay < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
The switch statement evaluates an expression and compares it against multiple possible values.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
default:
console.log("Weekend");
}
Loops are used to repeat a block of code multiple times as long as a condition is true.
The for loop allows you to repeat a block of code a certain number of times.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
The while loop executes a block of code as long as the specified condition is true.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
The do...while loop is similar to the while loop, but it guarantees at least one execution of the code block.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Loop control statements are used to modify the behavior of loops during execution.
The break statement exits a loop early, regardless of the loop's condition.
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break;
}
console.log(i);
}
The continue statement skips the current iteration of the loop and moves to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}