JavaScript Control Statements
What Are Control Statements?
Control statements allow your JavaScript code to make decisions. They let you run specific blocks of code based on certain conditions.
In short:
“If this is true, do that. Otherwise, do something else.”
if, else if, else
The if
statement is used to test a condition. If it evaluates to true
, the block of code inside runs.
Basic if Statement:
let score = 85;
if (score >= 80) {
console.log("Excellent!");
}
if…else Statement:
let score = 65;
if (score >= 80) {
console.log("Excellent!");
} else {
console.log("Keep practicing.");
}
if…else if…else:
When you want to test multiple conditions, use else if
.
let score = 70;
if (score >= 90) {
console.log("Outstanding");
} else if (score >= 75) {
console.log("Very Good");
} else if (score >= 60) {
console.log("Good");
} else {
console.log("Needs Improvement");
}
if…else Ladder
This is just a fancy name for chaining multiple else if
conditions as seen above.
Use it when you have several distinct conditions to check one after another.
Example:
let day = 2;
if (day === 1) {
console.log("Monday");
} else if (day === 2) {
console.log("Tuesday");
} else if (day === 3) {
console.log("Wednesday");
} else {
console.log("Another day");
}
switch Case
The switch
statement is another way to check multiple conditions, especially when you’re comparing the same variable against different values.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// fallback code
}
Example:
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Banana is yellow.");
break;
case "apple":
console.log("Apple is red.");
break;
case "grape":
console.log("Grape is purple.");
break;
default:
console.log("Unknown fruit.");
}
Important Note:
Use break
after each case to prevent fall-through (accidentally running multiple cases).
Ternary Operator Examples
The ternary operator is a shorthand way to write an if...else
statement in a single line.
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
Example 1: Basic Usage
let age = 20;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message); // "Adult"
Example 2: Nested Ternary
let marks = 85;
let grade = marks >= 90
? "A"
: marks >= 80
? "B"
: marks >= 70
? "C"
: "D";
console.log(grade); // "B"
Note:
Ternary operators are great for simple conditions, but avoid nesting too deeply—use if...else
if clarity is more important.
Summary
- Use
if
,else if
, andelse
to make decisions in your code. - Use
if...else ladder
when checking many related conditions. - Use
switch
for comparing one variable to multiple fixed values. - Use the ternary operator for short, clean one-line conditionals.