Reference · module 3
Decisions
Everything this module explains, on one page.
if and else
Make a program choose between branches.
- if (age >= 18) { ... } runs the code in the braces only when the condition in the round brackets is true. The brackets around the condition are required in JavaScript.
- else { ... } runs when the condition is false, and else if (...) checks another condition in between. Only the first branch whose condition is true runs; the rest are skipped.
- Comparisons give true or false: < and > compare, <= and >= include the edge, and !== means not equal. 5 >= 5 is true, 5 > 5 is false.
The mistake you are about to make
if (score = 10) {
if (score === 10) {
A single = reads as equals, like in maths. It is assignment: score becomes 10, the condition is always true, and nothing warns you.
=== and logic
Compare values safely and combine conditions.
- === checks that two values are equal and of the same type: 5 === 5 is true, 5 === "5" is false, because one is a number and the other is text.
- == converts types before comparing, so 5 == "5" is true and even 0 == "" is true. These surprises are why modern code uses === and !== almost everywhere.
- && means and: both sides must be true. || means or: one true side is enough. ! flips a value, so !true is false. age >= 18 && hasTicket needs both.
The mistake you are about to make
if (input == 0) {
if (Number(input) === 0) {
Double == looks like the normal comparison from other languages. It converts types, so an empty string from an input field also equals 0, and an empty form passes the zero check.
Truthy, falsy and ?:
Predict what if does with any value, and write short choices with ?:.
- if accepts any value, not just true and false. Six values count as false: false, 0, "" (the empty string), null, undefined and NaN. They are called falsy.
- Everything else is truthy, including some surprises: "0" and "false" are non-empty strings, and an empty array [] is still an object, so all three count as true.
- The ternary operator picks one of two values: condition ? a : b. const label = n > 0 ? "positive" : "not positive"; is a whole if and else in one line.
The mistake you are about to make
if (list) {
if (list.length > 0) {
An empty list feels like nothing, just like an empty string. But [] is truthy in JavaScript, so this condition passes for an empty list too. Check length.