| Conversion & Coercion in JavaScript :👈 | 👉:Javascript Loops |
JavaScript Flow Conditionals |
π JavaScript Flow Conditionals (if, else, switch)
1οΈβ£ if Statement
The if statement executes a block of code only if a specified condition is true.
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
// Output: You are an adult.
2οΈβ£ if...else Statement
The if...else statement provides an alternative block of code if the condition is false.
let score = 40;
if (score >= 50) {
console.log("You passed.");
} else {
console.log("You failed.");
}
// Output: You failed.
3οΈβ£ if...else if...else Statement
Use else if when you want to test multiple conditions.
let temp = 25;
if (temp > 30) {
console.log("It's hot.");
} else if (temp >= 20) {
console.log("It's warm.");
} else {
console.log("It's cold.");
}
// Output: It's warm.
4οΈβ£ switch Statement
The switch statement evaluates an expression and executes code based on matching cases.
Itβs often cleaner than writing many else if statements.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week.");
break;
case "Friday":
console.log("End of the workweek.");
break;
default:
console.log("It's a regular day.");
}
// Output: Start of the week.
β Quick Recap
- if β Runs code if condition is true.
- if...else β Runs one block if true, another if false.
- if...else if...else β Multiple conditions.
- switch β Cleaner way to handle many possible values of the same variable.
- Always use
breakin switch cases to prevent fall-through unless intentional.
π Mini Project: Grade Checker
let marks = 85;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else if (marks >= 50) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Output: Grade: B
| Conversion & Coercion in JavaScript :👈 | 👉:Javascript Loops |