Course outline · 0% complete

0/29 lessons0%

Course overview →

if, else if, else

lesson 3-1 · ~9 min · 7/29

Quiz

Warm-up from lesson 2-3: what does "7" === 7 evaluate to?

Braces instead of indentation

Branching is how a program makes decisions: charge shipping or not, show the data or an error. You already think in if/elif/else from Python, so this lesson is purely about the new spelling.

Python used a colon and indentation. JavaScript wraps the condition in parentheses and the body in curly braces { }. Indentation is just for humans here, the braces are what count.

const temp = 28;

if (temp >= 30) {
  console.log("Hot");
} else if (temp >= 20) {
  console.log("Warm");
} else {
  console.log("Cold");
}

The translation table from Python:

PythonJavaScript
elifelse if
and&&
or||
not x!x

Conditions are checked top to bottom and only the first true branch runs, exactly like Python.

Code exercise · javascript

Run it. temp is 28, so the first condition fails and the else if wins. The second if combines two conditions with && (and).

Code exercise · javascript

Your turn. Write a grade classifier: 90 or above prints A, 80 or above prints B, 70 or above prints C, anything else prints F. With score 87 it should print B.

Code exercise · javascript

Second practice. A movie ticket is sold when age is at least 17 OR withAdult is true. Print Ticket sold or Come back with an adult. With age 15 and withAdult true, the ticket sells.

The conditional operator: an if/else that is a value

JavaScript also has a compact operator for choosing between two VALUES: condition ? a : b gives a when the condition is true, otherwise b. It is called the ternary operator (ternary = it takes three parts), and it exists because an if/else is a statement, not a value — you cannot drop one into the middle of a template literal or a return. The ternary can go anywhere a value goes:

const age = 20;
const label = age >= 18 ? "adult" : "minor";
console.log(`Status: ${label}`);   // Status: adult

Python spells the same idea "adult" if age >= 18 else "minor". Use the ternary for one small choice between two values; the moment you want multiple statements or nested choices, a real if/else reads better.

Quiz

In Python you wrote: if a > 0 and b > 0. How does the condition look in JavaScript?