⬅ Previous Topic
JavaScript ExpressionsNext Topic ⮕
JavaScript Loops - for, while, do-while⬅ Previous Topic
JavaScript ExpressionsNext Topic ⮕
JavaScript Loops - for, while, do-whileControl flow in JavaScript determines the direction in which the code executes. By default, JavaScript runs code from top to bottom, but using control structures like if
, else
, and switch
, we can change this flow based on certain conditions.
The if
statement evaluates a condition. If it's true, it runs the associated block of code.
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
}
You are eligible to vote.
Q: What happens if the condition is false?
A: Nothing inside the if
block runs. Control moves to the next statement.
Use else
to define an alternative block that runs if the condition is false.
let temperature = 10;
if (temperature > 20) {
console.log("It's warm outside.");
} else {
console.log("It's cold outside.");
}
It's cold outside.
Use else if
to check multiple conditions in sequence. The first true condition will execute, and others will be skipped.
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
Grade: C
Q: What if more than one condition is true?
A: Only the first true condition is executed. Others are ignored.
The switch
statement is used when you want to compare one value against multiple possible matches.
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("You chose banana.");
break;
case "apple":
console.log("You chose apple.");
break;
case "mango":
console.log("You chose mango.");
break;
default:
console.log("Unknown fruit.");
}
You chose apple.
If you don't use break
, JavaScript continues to execute the next cases even if a match is found (this is called “fall-through”).
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
case "Tuesday":
console.log("Second day");
break;
}
Start of the week Second day
Tip: Always use break
unless you intentionally want fall-through behavior.
if
and else if
for range or boolean conditions.switch
for fixed values comparison (e.g., exact matches).break
in switch unless you need multiple cases to execute.⬅ Previous Topic
JavaScript ExpressionsNext Topic ⮕
JavaScript Loops - for, while, do-whileYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.