Control Structures in JavaScript
Control structures in JavaScript allow you to control the flow of your program. They include conditional statements (if-else, switch), loops (for, while, do-while), and error handling (try-catch).
If-Else Statements
The if-else
statement is used to execute a block of code based on a condition.
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Ternary Operator
The ternary operator is a shorthand for the if-else
statement.
let age = 20;
let message = age >= 18 ? "You are an adult." : "You are a minor.";
console.log(message); // Output: You are an adult.
Switch Statement
The switch
statement is used to execute one of many code blocks based on the value of an expression.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
}
Loops
Loops are used to execute a block of code repeatedly. JavaScript supports for
, while
,
do-while
, for...of
, and for...in
loops.
// For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While Loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// Do-While Loop
let x = 0;
do {
console.log(x);
x++;
} while (x < 5);
// For...of Loop (for arrays)
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
// For...in Loop (for objects)
let person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Error Handling: Try-Catch
The try-catch
statement is used to handle errors gracefully.
try {
let result = 10 / 0;
if (!isFinite(result)) {
throw new Error("Division by zero is not allowed.");
}
} catch (error) {
console.log(error.message); // Output: Division by zero is not allowed.
} finally {
console.log("Execution completed.");
}
Next: Functions