If, Else, Switch & Truthy/Falsy
if runs code only when a condition is true. Use it for decisions — login checks, age rules, empty cart warnings.
if Statement
if runs code only when a condition is true. Use it for decisions — login checks, age rules, empty cart warnings.
Real-life example: IF it is raining, THEN take an umbrella. Otherwise walk normally.
const score = 85;
if (score >= 60) {
console.log("Pass");
}else and else if
else runs when the if condition is false. else if checks another condition when the first one failed.
Real-life example: IF marks >= 90 → A grade, ELSE IF >= 75 → B grade, ELSE → practice more.
const marks = 72;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else {
console.log("Keep studying");
}switch Statement
switch compares one value to many cases. Use break after each case or execution falls through to the next.
Real-life example: A vending machine button — press 1 for chai, 2 for coffee, default for water.
const 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("Other day");
}Truthy and Falsy Values
In conditions, JavaScript treats some values as false: false, 0, "", null, undefined, NaN. Everything else is truthy.
Real-life example: An empty wallet ("" or 0) means "no money" in a condition. A wallet with even 1 rupee is truthy.
const name = "";
if (name) {
console.log("Hello " + name);
} else {
console.log("Please enter your name"); // runs
}
if ("Rishtaara") {
console.log("Non-empty string is truthy"); // runs
}