if Statement
The if statement runs a block of code only when a given condition is truthy.
const age = 18;
if (age >= 18) {
console.log("You can vote");
}
Try it Yourself โ
if...else
Add an else block to run code when the condition is falsy.
const age = 16;
if (age >= 18) {
console.log("You can vote");
} else {
console.log("Too young to vote");
}
Try it Yourself โ
else if for Multiple Conditions
Chain multiple conditions with else if.
const score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("Failing");
}
Try it Yourself โ
Ternary Operator
The ternary operator is a compact alternative for simple if...else expressions.
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Adult
Try it Yourself โ
Nested Ternary
You can nest ternaries, but use them sparingly for readability.
const score = 75;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
console.log(grade); // C
Try it Yourself โ
Short-Circuit Evaluation (AND)
The && operator returns the second operand if the first is truthy, otherwise the first operand. It short-circuits when the first value is falsy.
const user = { name: "Alice" };
console.log(user.name && "Hello " + user.name); // Hello Alice
const guest = null;
console.log(guest && "Hello " + guest); // null
Try it Yourself โ
Short-Circuit Evaluation (OR)
The || operator returns the second operand if the first is falsy, otherwise the first operand. It short-circuits when the first value is truthy.
const username = "";
const displayName = username || "Anonymous";
console.log(displayName); // Anonymous
Try it Yourself โ
Object-Based Conditional Logic
For complex branching, an object lookup can be cleaner than long if...else chains.
const actions = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b
};
const op = "multiply";
const result = actions[op] ? actions[op](10, 5) : "Unknown operation";
console.log(result); // 50
Try it Yourself โ