Definition: Control structures are the building blocks that control the flow of a program based on conditions and repetitions.
Meaning: They allow you to make decisions (like βif this, do thatβ), repeat tasks, or choose between options.
Purpose: To make your code dynamic and responsive by enabling decision-making, looping, and flow control.
Purpose: Execute a block of code only if a specific condition is true.
How it works: The condition inside parentheses if(condition) is evaluated.
If true, the code block inside curly braces {} runs. If false, it skips.
let age = 16;
if (age < 18) {
console.log("You are a minor.");
}
// Output: You are a minor.
Purpose: Choose between two alternatives. Run one block if the condition is true, otherwise run the other block.
How it works: If the condition in if() is true, run that block; if false,
run the block inside else.
let age = 20;
if (age < 18) {
console.log("You are a minor.");
} else {
console.log("You are an adult.");
}
// Output: You are an adult.
Purpose: Test multiple conditions in sequence, running the first block where the
condition is true, or the else block if none are true.
How it works: Checks conditions in order. When one is true, its block executes and the rest are skipped.
let age = 70;
if (age < 18) {
console.log("You are a minor.");
} else if (age < 60) {
console.log("You are an adult.");
} else {
console.log("You are a senior citizen.");
}
// Output: You are a senior citizen.
Use: Repeat a block of code multiple times until a condition is met.
Use: Exit or skip parts of loops or blocks.