if...else

Conditional Statements

Example

const hour = 15;
let greeting;
if (hour < 12) {
  greeting = "Good morning";
} else if (hour < 18) {
  greeting = "Good afternoon";
} else {
  greeting = "Good evening";
}
console.log(greeting);

Output

Good afternoon

Truthy Conditions and Guard Clauses

Example

Any value can be a condition. Returning early ("guard clauses") keeps code flat:

function discount(cart) {
  if (!cart.items.length) return "Cart is empty";
  if (cart.total < 500) return "No discount";
  return "10% off: ₹" + cart.total * 0.9;
}
console.log(discount({ items: [], total: 0 }));
console.log(discount({ items: ["pen"], total: 200 }));
console.log(discount({ items: ["bag"], total: 1200 }));

Output

Cart is empty
No discount
10% off: ₹1080