Programming Basics: Your First Steps

Lesson 3 of 5

Making Decisions with if/else

Programs need to react differently depending on the situation, that's what if/else is for.

JavaScript

The pieces

  • if (condition) { ... } runs its block only when condition is true.
  • else if (condition) { ... } checks another condition, only if every earlier one was false.
  • else { ... } runs when none of the earlier conditions matched, it's the fallback.
  • Conditions are usually built from comparison operators (>=, ===, ...) and can be combined with && (and, both must be true) and || (or, at least one must be true).
JavaScript

Truthy and falsy

Values other than actual booleans still work inside an if, 0, "" (empty string), and null all act like false, almost everything else acts like true. This is handy for quick checks like if (name) { ... } (runs only if name isn't empty), but can also be surprising if you're not expecting it.

📝 if/else Quiz

Passing score: 70%
  1. 1.Which operator requires BOTH sides to be true for the whole expression to be true?

  2. 2.An ____ block runs only when every earlier if/else if condition was false.

  3. 3.An empty string "" behaves like false inside an if condition.