condition and loop
In JavaScript, conditions and loops are fundamental constructs that control the flow of execution in scripts. Conditions allow the execution of code segments based on whether a certain criterion is met, while loops repeat a code segment based on a condition or until a certain criterion is met. Let's explore both, along with examples:
Conditions:
if...else statement - Executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
let temperature = 20;
if (temperature < 25) {
console.log("It's cool outside.");
} else {
console.log("It's warm outside.");
}
// Output: It's cool outside.
else if statement - Used to specify a new condition if the first condition is false.
let score = 70;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 70) {
console.log("Grade B");
} else {
console.log("Grade C");
}
// Output: Grade B
switch statement - Evaluates an expression, matches the expression's value to a case clause, and executes statements associated with that case.
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;
case 6:
console.log("Saturday");
break;
case 7:
console.log("Sunday");
break;
default:
console.log("Invalid Day");
}
// Output: Wednesday
Loops:
for loop - Repeats a block of code a specified number of times.
for (let i = 0; i < 3; i++) {
console.log("Number " + i);
}
// Output: Number 0, Number 1, Number 2
while loop - Repeats a block of code while a specified condition is true.
let i = 0;
while (i < 3) {
console.log("Number " + i);
i++;
}
// Output: Number 0, Number 1, Number 2
do...while loop - Also repeats a block of code while a specified condition is true but guarantees the code to be executed at least once.
let i = 0;
do {
console.log("Number " + i);
i++;
} while (i < 3);
// Output: Number 0, Number 1, Number 2
for...in loop - Iterates over the enumerable properties of an object.
const car = {make: "Ford", model: "Mustang", year: 1969};
for (let prop in car) {
console.log(`${prop}: ${car[prop]}`);
}
// Output: make: Ford, model: Mustang, year: 1969
for...of loop - Iterates over iterable objects such as arrays and strings.
const colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// Output: red, green, blue
Combining conditions and loops is a powerful technique, allowing for complex logic to be expressed cleanly and efficiently. Depending on the scenario, you might use conditions to determine when loops should start or end or what logic should be performed within a loop.