JavaScript is one of the most widely used programming languages, and today I took my first steps into a key concept: conditional statements. These are used to perform different actions based on different conditions.
π§© What Are Conditional Statements?
Conditional statements allow a program to make decisions. You can think of them like βif this happens, do that.β
In JavaScript, the most common conditional statements are:
if
else if
else
switch
β
if
Statement
The if
statement checks a condition. If itβs true, it runs a block of code.
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
π Output: You are an adult.
π else if
and else
When you have more than one condition, you can use else if
and else
.
let time = 14;
if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
π Output: Good afternoon!
π switch
Statement
The switch
statement is useful when you have many conditions based on the same variable.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
π Output: Wednesday
π‘ TIL Summary
- Conditional statements control the flow of logic.
- Use
if
for one condition,else if
for multiple, andelse
for a fallback. - Use
switch
when checking the same variable for different values.
Top comments (0)