T4 JavaScript · Lesson 2
Operators and conditionals
Comparing values with ===, and why == is avoided; combining questions with &&, || and !; the values that count as false; and making a program choose, with if, else if and else, the ternary operator and switch.
- compare values with ===, !==, <, >, <= and >=, and say why == is avoided
- compare strings, and avoid the traps of text against numbers, NaN and chained comparisons
- combine conditions with &&, || and !, and read what they give back
- say which values are falsy and which truthy, and give a default with ?? or ||
- make a program choose with if, else if and else
- choose a value with the ternary operator, and one of many paths with switch
The back cover
A program that cannot choose does the same thing every time. Real programs ask questions: is the passenger a child, is the ticket for today, did the payment go through. Each question gives a yes or a no, and the program takes a different road for each.
These pages show how to compare values with === and why == is avoided, and how to join questions with &&, || and !. They list the values that count as false. They make a program choose with if, else if and else, with the ternary operator for a value, and with switch for a list of exact answers.
Before you start
The story: A horn that would not sound
Fog comes in from the sea so thick that the lamps of the quay are only smudges. Ships feel their way into Brasshaven by sound, listening for the great horn on the harbour wall. Tonight the horn is silent. Last Tuesday, on a clear afternoon, it boomed twice for no reason, and every fishing boat dropped anchor where it was.
Master Hakim Verge has the horn's clockwork open on his bench. Every minute its script reads a number from the fog-glass, and then decides. "It must sound when the glass reads under 200 paces," he says, "and only then. A clock that cannot decide is worse than no clock at all."
Corin reads the script and says that it looks right. That, says Master Verge, is how every broken script looks.
A program that only works things out is like a calculator. A program that decides is something more: it can turn the horn on in fog and leave it off in sun, give a discount to members only, or show a different message to a student who passed. This lesson teaches the questions code asks, and how it acts on the answers.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Booleans. | typeof true gives boolean. | Every comparison gives one. |
| === asks "is exactly equal to?" | 2 + 2 === 4 gives true. | With !==, <, >, <= and >=. |
| Types. | "5" is a string; 5 is a number. | Comparing values of two types. |
| NaN. | Number("abc") gives NaN. | It equals nothing, not even itself. |
| undefined and null. | let seat; holds undefined. | Both count as false in a question. |
| The empty string. | "" has length 0. | It counts as false too. |
| Converting. | Number("42") gives 42. | Readings are converted before comparing. |
| The remainder. | 7 % 2 gives 1. | Even or odd, and leap years. |
| Template literals. | `Hi ${name}` | With a choice inside a gap. |
| String methods. | " Asha ".trim().toLowerCase() | Comparing names fairly. |
| = means "is set to". | let x = 5; | It is not a question, and that matters in an if. |
| The order of operations. | 2 + 3 * 4 gives 14. | Comparisons and logic have places in it too. |
By the end of this lesson you will be able to:
- compare values with
===,!==,<,>,<=and>=, and say why==is avoided; - compare strings, and avoid the traps of text against numbers, NaN and chained comparisons;
- combine conditions with
&&,||and!, and read what they give back; - say which values count as false and which as true, and give a default with
??or||; - make a program choose with
if,else ifandelse; - choose a value with the ternary operator, and one of many paths with
switch.
How to follow this lesson
Every block on this page runs. When a condition surprises you, print it on its own: console.log(reading < 200); shows the exact true or false that the program acted on. Most bugs in this lesson are a question that gave a different answer from the one you expected.
In one line
Programs decide by asking questions that have true or false answers, then running different code for each answer.
Comparing values
At a glance
A ticket checker on a train asks questions all day. Is this the right train number? Is the passenger under 12, for a child's fare? Each question has one of two answers, and in code each answer is a boolean.
Comparison operators such as <, > and === give back true or false. Use === and !==, never ==, and convert types on purpose first. Strings compare character by character by their codes, so convert numbers that arrive as text, and remember that NaN equals nothing, not even itself.
Take a guess: Is "10" < "9" true or false in JavaScript?
A ticket checker on a train asks questions all day. Is this the right train number? Is the passenger under 12, for a child's fare? Is the ticket for today? Each question has one of two answers, yes or no. In code, each answer is a boolean: true or false.
An operator that compares two values and gives back a boolean. 5 < 7 asks "is 5 less than 7?" and gives true.
| Write | Read it aloud | Example | Gives |
|---|---|---|---|
=== | is exactly equal to | 5 === 5 | true |
!== | is not exactly equal to | 5 !== 6 | true |
< | is less than | 3 < 5 | true |
> | is greater than | 7 > 9 | false |
<= | is less than or equal to | 5 <= 5 | true |
>= | is greater than or equal to | 7 >= 7 | true |
console.log(5 === 5, 5 === "5", 5 !== 6, 3 < 5, 5 <= 5, 7 > 9, 7 >= 7);
true false true true true false true
Look at the second answer. 5 === "5" is false, because === checks the type as well as the value. A number and a string are never exactly equal, however alike they look. That strictness is what you want: a reading of "5" from a page is not yet the number 5.
A comparison is an expression like any other, and its answer is a value of the type boolean:
console.log(typeof (5 > 3), typeof 5 === "number");
boolean true
Why == is avoided
JavaScript has a second, older pair of equality operators: == and !=. They are called loose equality, because they convert the two values to a common type before comparing. The rules for that conversion are long, and they give answers that surprise almost everyone:
console.log(5 == "5", 0 == "", 0 == false, null == undefined, null == 0, "" == false);
true true true true false true
Zero equals the empty string, and the empty string equals false, yet null does not equal 0. Nobody remembers all of these rules, and nobody needs to. Working programmers follow one habit instead.
Always three
Use === and !==, never == and !=. If two values may be of different types, convert one on purpose first, as the values lesson showed: Number(reading) === 5.
NaN equals nothing
NaN, the result of failed arithmetic, has one more oddity. It is not equal to anything, not even to itself:
console.log(null === undefined, NaN === NaN, Number.isNaN(NaN));
false false true
So x === NaN is false for every x, and can never find a NaN. Ask with Number.isNaN(x) instead, as the values lesson did.
Comparing strings
Strings can be compared with < and > too. They are compared the way a dictionary orders words: first character against first character, and only if those are the same, the second against the second, and so on. "abc" comes before "abd" because c comes before d, and "a" comes before "ab" because it runs out first.
But the order is not quite a dictionary's. Each character has a number, called its character code, and the codes decide. Capital letters have smaller codes than small letters, and the digits come before both:
console.log("A".charCodeAt(0), "Z".charCodeAt(0), "a".charCodeAt(0), "1".charCodeAt(0), "2".charCodeAt(0));
65 90 97 49 50
console.log("apple" < "banana", "Zebra" < "apple", "2" > "12", "abc" < "abd", "a" < "ab");
true true true true true
"Zebra" comes before "apple", because Z is 90 and a is 97. And "2" is greater than "12": as text, the first characters are compared, 2 against 1, and 2 is greater. The rest of the string never gets a say. This is the trap in the fog horn's script.
When one side is a number and the other a string, < and > turn the string into a number first. Only two strings are compared as text:
console.log("10" < 9, "10" < "9", 10 < 9);
false true false
A common mistake
Comparing numbers that are still text. Readings from a page, a file or a device often arrive as strings, and "1200" < "200" is true, because 1 comes before 2. Convert the readings with Number(...) as they arrive, and the comparison is between numbers.
console.log("1200" < "200", 1200 < 200, Number("1200") < 200);
true false false
Capitals matter in equality too. "Asha" === "asha" is false. To compare names fairly, bring both sides to the same form first, with the string methods of the values lesson:
const typed = " Asha ";
console.log(typed === "asha", typed.trim().toLowerCase() === "asha");
false true
Two traps with numbers
In mathematics you may write 1 < x < 10 to say that x is between 1 and 10. In JavaScript the same line runs, and means something else. It works from left to right, one comparison at a time:
console.log(1 < 20 < 10, 10 > 5 > 1);
true false
Take the first one slowly. 1 < 20 is true. Then true < 10 compares a boolean with a number, so true becomes 1, and 1 < 10 is true. So 20 seems to be between 1 and 10. The second one goes the other way: 10 > 5 is true, true becomes 1, and 1 > 1 is false. To ask whether x lies between two numbers, ask two questions and join them with &&, as the next section shows.
The other trap is an old one: decimals that are not stored exactly. 0.1 + 0.2 === 0.3 is false, because the sum is 0.30000000000000004. Compare money in paise, where every value is a whole number and comparisons are exact.
console.log(0.1 + 0.2 === 0.3, 10 + 20 === 30);
false true
Worked example 1
A grocery app gives free delivery on orders of ₹499 or more. Write the question for three baskets: ₹498, ₹499 and ₹650.
What we have: three totals, and the rule "₹499 or more"
What we need: true or false for each basket
The plan: "or more" includes 499 itself, so the operator is >=, read "is greater than or equal to"
- A basket of ₹499 must qualify, so > would be wrong: 499 > 499 is false.
- >= includes the edge: 499 >= 499 is true.
console.log(498 >= 499, 499 >= 499, 650 >= 499);
false true true
false, true, true: the ₹499 and ₹650 baskets get free delivery.
Check: test the edge first. The ₹499 basket is the one most likely to be got wrong, and it qualifies, as the rule says.
A path that fails: writing total > 499. It looks right, and every test with a round number such as 650 passes, but a customer with exactly ₹499 is charged for delivery.
Worked example 2
The fog horn's script reads the fog-glass as text, such as "1200", and asks reading < "200". On a clear day the glass reads 1200 paces, and the horn sounds. Why, and what is the fix?
What we have: a reading that arrives as the string "1200", and a limit of 200 paces
What we need: a comparison that is false for 1200 and true for anything under 200
The plan: find the types on both sides, then make both numbers
- Both sides are strings, so they are compared as text, character by character.
- The first characters are 1 and 2. 1 comes first, so "1200" counts as less than "200", and the horn sounds.
- Convert the reading as it arrives, and compare it with the number 200:
const reading = "1200";
const paces = Number(reading);
console.log(reading < "200", paces < 200);
true false
As text the answer is true, so the horn sounded; as numbers it is false, and the horn stays quiet on a clear day.
Check: a reading of 150 must still sound the horn: Number("150") < 200 is true.
A path that fails: comparing the text reading with the number 200, as "1200" < 200. That happens to work, as < turns the string into a number, but the next person to read the code cannot see that, and a reading such as "1,200" would become NaN, which is never less than anything.
When you are stuck: a comparison gives the wrong answer
Print both sides with their types: console.log(a, typeof a, b, typeof b);. Two strings are compared as text.
Check for NaN: it makes every comparison false, so test it with Number.isNaN.
Check capitals and spaces in strings. Compare trim().toLowerCase() forms.
Check for a chained comparison such as 1 < x < 10. Split it into two questions joined with &&.
Your turn
console.log(7 === 7.0, "7" === 7, 3 <= 3, "b" > "a", "B" > "a");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true false true true false
- 7 and 7.0 are the same number: true.
- "7" is a string and 7 a number: never exactly equal.
- 3 is equal to 3, so less than or equal holds: true.
- b comes after a: true.
- Capital B has a smaller code than small a: false.
It prints true false true true false.
Which of these is true: "100" < "20" or 100 < 20?Tap to reveal
- Two strings are compared as text: 1 against 2, and 1 comes first, so "100" < "20" is true.
- Two numbers: 100 is not less than 20, so 100 < 20 is false.
console.log("100" < "20", 100 < 20);
true false
Only the string comparison, "100" < "20", is true.
A value x holds NaN. What do x === x and Number.isNaN(x) give?Tap to reveal
- NaN is not equal to anything, not even itself, so x === x is false.
- Number.isNaN asks the right question: true.
const x = Number("abc");
console.log(x === x, Number.isNaN(x));
false true
x === x is false, and Number.isNaN(x) is true.
Did you know?
Three ways to ask equal
JavaScript has three ways to ask whether two values are the same. MDN lists them: === for strict equality, == for loose equality, which converts types first, and Object.is(). The last differs from === in two corners: Object.is(NaN, NaN) is true, and Object.is(-0, 0) is false. Most code needs only ===.
Why it fits here: It places this topic's rule in context: === is the everyday choice, == is avoided, and Object.is is kept for rare corners.
Sources: MDN: Equality comparisons and sameness; MDN: Object.is(); ECMAScript Language Specification: Object.is
Capitals first
Every capital letter sorts before every small one, so "Zebra" < "apple" is true. Strings are compared by their UTF-16 code units, and in those codes the capitals come first. The order goes back to ASCII, first published in 1963, whose designers put the small letters in later columns, so that a letter's two cases differ by a single bit.
Why it fits here: It is why this topic converts text before comparing: by codes, "Zebra" comes before "apple", and "10" before "9".
Sources: MDN: Less than (<); Wikipedia: ASCII
In one line
Comparisons give booleans. Use === and !==, never ==, and convert types on purpose first. Strings compare character by character by their codes, so convert numbers that arrive as text, and remember that NaN equals nothing.
And, or, not: joining questions
At a glance
A cinema's doorman lets you in if you have a ticket and it is for this show. A lift's doors open if someone presses the button or someone stands in the doorway. Real decisions join questions, and code joins them with three operators.
The && operator needs both answers true, || needs at least one, and ! turns an answer around. They work after the comparisons, && before ||, and they stop as soon as the answer is known. Because && and || give back one of their two values, name || "Guest" gives a default.
Take a guess: If the first part of an && is false, does JavaScript look at the second?
A cinema's doorman lets you in if you have a ticket and it is for this show. A lift's doors open if someone presses the button or someone stands in the doorway. A conductor tells you not to board if the train is full. Real decisions often join two or more questions, and code joins them with three operators.
An operator that joins or turns around true-or-false answers. && is read "and", || is read "or", and ! is read "not".
| a | b | a && b: both | a || b: at least one | !a: the opposite |
|---|---|---|---|---|
true | true | true | true | false |
true | false | false | true | false |
false | true | false | true | true |
false | false | false | false | true |
console.log(true && true, true && false, false || true, false || false, !true, !false);
true false true false false true
A way to remember them: && is fussy, and wants both to be true. || is easy-going, and is happy with either. ! turns any answer around. On an Indian or American keyboard, the stroke | is on the key above Enter, typed with Shift.
Joining comparisons
The logical operators are most useful for joining comparisons. A visitor over 18 who holds a ticket may enter:
const age = 20;
const hasTicket = true;
console.log(age >= 18 && hasTicket);
true
This is also the cure for the chained comparison of the last section. To ask whether x lies between 1 and 10, ask two questions and join them. To ask whether it lies outside, use || instead:
const x = 15;
console.log(x >= 1 && x <= 10, x < 1 || x > 10);
false true
Which goes first
When several operators meet in one line, JavaScript works in a fixed order. ! comes first of all, because it sits right against the one value after it. Then come the arithmetic, then the comparisons, then &&, and || last of all.
console.log(true || false && false, (true || false) && false);
true false
In the first, && goes before ||, so false && false is worked out first, giving false, and then true || false gives true. In the second, the brackets make || go first, giving true, and then true && false gives false. When a line mixes && and ||, add brackets even where they are not needed. They cost nothing, and the next reader does not have to remember the order.
Because ! goes first, !0 + 1 means (!0) + 1: not 0 is true, and true + 1 is 2. To turn around the answer of a whole sum or comparison, put it in brackets after the !:
console.log(!0 + 1, !(0 + 1));
2 false
! in front of brackets turns the whole answer around:
console.log(!(5 > 3), !(5 > 3 && 2 > 1), !(5 > 3) || !(2 > 1));
false false false
The last two always agree. "Not both" is the same as "one or the other is not". This rule has a name, De Morgan's law, after the nineteenth-century mathematician Augustus De Morgan, and it helps whenever a long condition with a ! in front is hard to read.
Stopping early
&& and || do not always look at both sides. If the left side of && is false, the answer must be false, whatever the right side holds, so JavaScript never works the right side out. If the left side of || is true, the answer must be true, and again the right side is skipped. This is called short-circuit evaluation.
Short-circuiting is useful, because it can guard a step that would fail. Reading something from null is an error:
const user = null;
console.log(user.name);
Uncaught TypeError: Cannot read properties of null (reading 'name')
at line 2
Put the question "is there a user?" in front with &&, and the dangerous step is skipped when the answer is no. Modern JavaScript also has a short form for this guard, ?., called optional chaining: read user?.name as "user's name, if there is a user". It gives undefined instead of an error:
const user = null;
console.log(user?.name, user && user.name);
undefined null
What && and || give back
Here is a fact that surprises many people. && and || do not always give back true or false. They give back one of the two values they were given: the one that decided the answer.
console.log("Asha" || "Guest", 0 || 10, null || "none", "x" && "y", 0 && "never");
Asha 10 none y 0
|| gives back its first value if that value counts as true, and otherwise its second value. && gives back its first value if that value counts as false, and otherwise its second. Which values count as true and which as false is the subject of the next section. This behaviour is how JavaScript programs give a value a default: name || "Guest" is the name if there is one, or Guest if not.
Worked example 3
A year is a leap year if it can be divided by 4, except that years divisible by 100 are not, unless they are also divisible by 400. Write the rule as one condition, and test it on 2024, 1900 and 2000.
What we have: the rule in words, and three years to test
What we need: one condition that is true for leap years only
The plan: turn each part of the rule into a comparison with %, the remainder, then join the parts with && and ||
- "Can be divided by 4" means the remainder after dividing by 4 is 0:
y % 4 === 0. - "Except years divisible by 100" joins a second question with &&:
y % 100 !== 0. - "Unless also divisible by 400" is a second way to be a leap year, so it joins with ||:
y % 400 === 0. Brackets keep the first two parts together.
let y = 2024;
console.log(y, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0);
y = 1900;
console.log(y, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0);
y = 2000;
console.log(y, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0);
2024 true
1900 false
2000 true
The condition is (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0: 2024 and 2000 are leap years, and 1900 is not.
Check: 1900 is divisible by 4 and by 100 but not by 400, so it is the case that tests the exception, and it gives false as it should.
A path that fails: testing only y % 4 === 0. It passes for 2024 and 2000, the years most people try, and wrongly makes 1900 a leap year. Test the awkward cases of a rule, not only the common ones.
Worked example 4
A hall lets in adults who hold a ticket, and also any guest of the organisers, whatever their age. Asha is 20, has no ticket, and is a guest. Write the condition, and check that it lets her in.
What we have: an age of 20, no ticket, and a guest pass
What we need: true for Asha
The plan: join the adult-with-ticket rule with &&, and then join the guest rule with ||, using brackets to show which goes with which
const age = 20;
const hasTicket = false;
const isGuest = true;
console.log((age >= 18 && hasTicket) || isGuest);
true
- Without the guest pass she would be turned away, as she has no ticket. The pass, joined with ||, is enough on its own.
The condition (age >= 18 && hasTicket) || isGuest gives true.
Check: a 15-year-old guest is let in too, and a 20-year-old with neither a ticket nor a pass is not.
A path that fails: putting the brackets in the wrong place: age >= 18 && (hasTicket || isGuest). It gives true for Asha too, but it turns away a 15-year-old guest, which breaks the rule "whatever their age". Two conditions that agree on one case can still differ on another.
When you are stuck: a joined condition is always true, or never true
Print each part on its own: console.log(age >= 18, hasTicket, isGuest);.
Check && against ||. "Both" is &&; "either" is ||.
Put brackets around each group of a long condition, so that the order is the one you meant.
Look for a chained comparison, such as 1 < x < 10, which needs && between two questions.
Your turn
const t = true;
const f = false;
console.log(t && !f, !t || f, !(t && f));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true false true
- t && !f: not false is true, and true && true is true.
- !t || f: not true is false, and false || false is false.
- !(t && f): t && f is false, and not false is true.
It prints true false true.
Write a condition that is true when a temperature t is below 15 or above 35, and test it with 10, 25 and 40.Tap to reveal
- Outside a range is "below the low end or above the high end": ||.
let t = 10;
console.log(t < 15 || t > 35);
t = 25;
console.log(t < 15 || t > 35);
t = 40;
console.log(t < 15 || t > 35);
true
false
true
t < 15 || t > 35 gives true, false, true.
What do "" || "Guest" and "Asha" && "Guest" give?Tap to reveal
- || gives its first value if it counts as true. An empty string counts as false, so it gives its second value.
- && gives its second value when the first counts as true, and Asha does.
console.log("" || "Guest", "Asha" && "Guest");
Guest Guest
Both give Guest.
Did you know?
Laws from a man born in Madurai
Two rules for turning questions around carry the name of a man born in India. Augustus De Morgan was born on 27 June 1806 in Madura, now Madurai in Tamil Nadu, and became the first professor of mathematics at University College London. De Morgan's laws say that not (a and b) means (not a) or (not b). In JavaScript, !(a && b) equals !a || !b.
Why it fits here: It gives this topic a tool: to turn a joined question around, flip each part and swap && with ||.
Sources: MacTutor History of Mathematics: Augustus De Morgan; Wikipedia: De Morgan's laws
Why && has two signs
The && and || signs were added on purpose. In B, the language before C, a single & and | did this job, with a special meaning inside if statements that was difficult to explain and use. Dennis Ritchie writes that, at the suggestion of Alan Snyder, he introduced && and || to make the mechanism more explicit. JavaScript writes them the same way.
Why it fits here: It explains this topic's stopping rule: && and || were made for exactly this, to stop as soon as the answer is known.
Source: Dennis M. Ritchie: The Development of the C Language
In one line
&& needs both answers true, || needs at least one, and ! turns an answer around. They work after the comparisons, && before ||, and they stop as soon as the answer is known. && and || give back one of their two values, so name || "Guest" gives a default.
Truthy and falsy: what counts as yes
At a glance
A shopkeeper asks whether you brought a bag, and you hold up an empty one. Strictly the answer is yes, but for carrying vegetables it may as well be no. JavaScript treats empty and nothing as no in the same way.
Eight values count as false: false, 0, -0, 0n, the empty string, null, undefined and NaN. Every other value counts as true, "0" and [] included. When 0 or an empty string is a real answer, use ??, which replaces only null and undefined.
Take a guess: Is the string "0" treated as true or as false in an if?
A shopkeeper asks, "Did you bring a bag?" You hold up a bag with nothing in it. Strictly, the answer is yes. But for carrying vegetables it may as well be no. People treat "empty" and "nothing" as no all the time, and JavaScript does the same.
When a value that is not a boolean is used where a true or false answer is needed, as in an if or with &&, JavaScript treats it as one or the other. Only a few values count as false. Every other value counts as true.
Counting as false in a condition. Exactly eight values are falsy: false, 0, -0, 0n, "", null, undefined and NaN.
Counting as true in a condition. Every value that is not falsy is truthy, including "0", "false", a space, [] and {}.
Boolean(...) shows how any value would count, without using it in a condition:
console.log(Boolean(0), Boolean(""), Boolean(null), Boolean(undefined), Boolean(NaN), Boolean(0n), Boolean(-0), Boolean(false));
false false false false false false false false
console.log(Boolean("0"), Boolean("false"), Boolean(" "), Boolean([]), Boolean({}), Boolean(-1), Boolean(Infinity));
true true true true true true true
The second line holds the traps. The string "0" is truthy, because it is a string with one character in it, not the number 0. The string "false" is truthy for the same reason. An empty list [] is truthy, although it holds nothing. Only the eight values in the box count as false. MDN's list adds one more, document.all, an old object of browsers kept falsy for the sake of very old pages; you will not meet it in new code.
Two exclamation marks are a short form of Boolean(...) that you will see in other people's code. The first ! turns the value into the opposite boolean, and the second turns it back:
console.log(!!"hi", !!0, !"", !"hi");
true false true false
Truthy values in a condition
Using a value on its own as a condition is a short way of asking "is there something here?". An empty box on a form gives the empty string, which is falsy:
const typed = "";
if (typed) {
console.log("got it");
} else {
console.log("empty box");
}
empty box
The if statement is the subject of the next section; here it is enough to see that the falsy empty string sent the program down the else path.
A common mistake
Asking "is there a value?" when 0 is a real value. A count of 0 visitors, a price of ₹0 or a reading of 0 paces are real answers, but 0 is falsy, so a condition such as if (reading) treats them as missing. This is the trap that kept the fog horn silent in the thickest fog.
const reading = 0;
if (reading && reading < 200) {
console.log("sound the horn");
} else {
console.log("silent");
}
silent
The script meant reading && to skip a missing reading. A reading of 0, the thickest fog of all, is falsy too, so the horn stayed silent exactly when it mattered most. The cure is to ask the real question, "is the reading missing?", in so many words:
const reading = 0;
if (reading !== undefined && reading < 200) {
console.log("sound the horn");
} else {
console.log("silent");
}
sound the horn
Defaults: || and ??
The last section showed that name || "Guest" gives a default. It works because || gives back its second value when the first is falsy. But for numbers it has the same weakness as the fog horn: a real 0 is falsy, and gets replaced.
let count = 0;
console.log(count || "none", count ?? "none");
none 0
Either null or undefined: the two values that mean "there is no value". 0, the empty string and false are not nullish.
The operator ?? is called nullish coalescing. Read count ?? "none" aloud as "count, or none if count is missing". It gives back its second value only when the first is null or undefined, so a real 0 or an empty string is kept:
console.log(0 ?? 10, null ?? "Guest", undefined ?? 5, ("" ?? "empty") === "");
0 Guest 5 true
Several ?? can be joined, and the first value that is not missing wins:
console.log(null ?? 0 ?? 5, undefined ?? null ?? "last");
0 last
| Use | When | Example |
|---|---|---|
|| | any falsy value should be replaced, such as an empty name | name || "Guest" |
?? | only a missing value should be replaced, and 0 or "" are real | score ?? "none yet" |
Worked example 5
A quiz app shows each player's score, or the words none yet before the player has a score. Asha has scored 0 so far. Write the text for her.
What we have: a score of 0, which is a real score
What we need: the text Score: 0, not Score: none yet
The plan: choose the operator that replaces only a missing value
- With ||, the 0 is falsy, so it is replaced. With ??, it is kept, as 0 is not nullish.
const score = 0;
console.log(`Score: ${score || "none yet"}`, `Score: ${score ?? "none yet"}`);
Score: none yet Score: 0
- A player with no score at all has the score undefined, and ?? gives none yet for that player, as it should:
let score;
console.log(`Score: ${score ?? "none yet"}`);
Score: none yet
Score: 0, with score ?? "none yet".
Check: the two cases that matter both come out right: 0 shows as 0, and undefined shows as none yet.
A path that fails: writing score || "none yet". It looks the same in every test with a score above 0, and tells a player who scored 0 that they have no score.
Worked example 6
A sign-up page asks for an optional nickname. If the box is left empty, the page should greet the person by their name, Asha. Which operator gives the right greeting?
What we have: a nickname box that gives the empty string when left empty, and the name Asha
What we need: the nickname if one was typed, and Asha otherwise
The plan: decide whether the empty string counts as missing here
- An empty box means no nickname, so the empty string must be replaced. That is a job for ||, which replaces every falsy value.
const nickname = "";
const name = "Asha";
console.log(`Hello, ${nickname || name}!`, `Hello, ${nickname ?? name}!`);
Hello, Asha! Hello, !
||: it gives Hello, Asha!, while ?? keeps the empty string and greets nobody.
Check: a typed nickname such as Ashu is truthy, so || keeps it.
Another way: trim the box first, so that a nickname of only spaces counts as empty too: nickname.trim() || name.
When you are stuck: a value is treated as missing, or as present, when it should not be
Ask what the value is with Boolean(x). The eight falsy values are the only ones that count as false.
If 0 or "" is a real answer, do not use the value on its own as a condition. Ask x !== undefined, or use ??.
Remember that "0" and "false" in quotes are strings with characters in them, so they are truthy.
Print the condition itself: console.log(reading && reading < 200);.
Your turn
console.log(Boolean("0"), Boolean(0), "" || "x", 0 ?? "x", null ?? "x");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true false x 0 x
- "0" is a string with a character in it: truthy.
- 0 is one of the eight falsy values.
- The empty string is falsy, so || gives x.
- 0 is not nullish, so ?? keeps it.
- null is nullish, so ?? gives x.
It prints true false x 0 x.
Which of these are falsy: "false", 0, " ", NaN, [], null?Tap to reveal
- "false" is a non-empty string: truthy.
- 0 is falsy.
- " " holds a space, so it is not empty: truthy.
- NaN is falsy.
- [] is an object: truthy.
- null is falsy.
0, NaN and null are falsy.
A shop's discount is kept in a name called discount, and some items have a discount of 0. Write the text Discount: 0% for such an item, and Discount: none for an item whose discount is undefined.Tap to reveal
- 0 is a real discount, so use ??, which replaces only null and undefined.
let discount = 0;
console.log(`Discount: ${discount ?? "none"}${discount === undefined ? "" : "%"}`);
discount = undefined;
console.log(`Discount: ${discount ?? "none"}${discount === undefined ? "" : "%"}`);
Discount: 0%
Discount: none
discount ?? "none" keeps the 0 and replaces only a missing discount. The ternary that adds the % sign is the subject of the section after next.
Did you know?
The one falsy object
There is one falsy object, and it exists for old websites. MDN notes that the only falsy object in JavaScript is the built-in document.all. The standard makes room for it: objects with a special [[IsHTMLDDA]] slot behave like undefined when turned into a boolean. Its note says that document.all has this slot and exists for web compatibility purposes.
Why it fits here: It is the single exception to this topic's rule that every object is truthy, kept so that very old pages still work.
Sources: MDN Glossary: Falsy; ECMAScript Language Specification: The [[IsHTMLDDA]] Internal Slot
A young operator for real zeros
The ?? operator is young. TC39's list of finished proposals places nullish coalescing in ECMAScript 2020, with Gabriel Isenberg as its champion, and MDN marks it as working across browsers since July 2020. It returns its right side only when the left side is null or undefined, so a real 0 or an empty string survives.
Why it fits here: It is the tool this topic offers for real zeros: || replaces every falsy value, while ?? replaces only the two kinds of nothing.
Sources: TC39: Finished Proposals; MDN: Nullish coalescing operator (??)
In one line
Eight values are falsy: false, 0, -0, 0n, the empty string, null, undefined and NaN. Every other value is truthy, "0" and [] included. When 0 or "" is a real answer, ask x !== undefined or use ??, which replaces only null and undefined.
Making a choice with if
At a glance
If it rains, take an umbrella; otherwise, wear a cap. You make choices like this all day: a question, something to do when the answer is yes, and something else to do when it is no. Code has a statement with exactly that shape.
An if runs its block when the condition is truthy, and an else runs when it is not. In a chain of else if, the first true question wins, so ask the narrowest first. Always write the braces, and never a single = inside a condition.
Take a guess: In a chain of else if, which block runs when two conditions are true?
"If it rains, take an umbrella. Otherwise, wear a cap." You make choices like this all day, without thinking about their shape: a question, something to do when the answer is yes, and something else to do when it is no. Code has a statement with exactly that shape.
A statement that runs a block of code only when its condition is truthy. Its shape is if (condition) { ... }: the word if, the condition in round brackets, and the code to run in curly braces.
Lines of code between a pair of curly braces, { and }, that run together. The lines inside a block are indented by two spaces, so that the eye can see where it starts and ends.
const raining = true;
if (raining) {
console.log("Take an umbrella");
}
console.log("Off you go");
Take an umbrella
Off you go
The condition was true, so the block ran. The last line is outside the block, so it runs either way. Change true to false and run it again: only Off you go is printed.
else: the other path
An else block after an if runs when the condition is falsy. Exactly one of the two blocks runs, never both, and never neither.
const raining = false;
if (raining) {
console.log("Take an umbrella");
} else {
console.log("Wear a cap");
}
Wear a cap
else if: more than two paths
Many choices have more than two answers. A traffic light can be red, yellow or green. Put else if between the if and the else, as many times as you need. JavaScript asks the questions in order, from the top, and runs the block of the first one that is true. The rest are skipped, even if they are true too.
const light = "green";
if (light === "red") {
console.log("Stop");
} else if (light === "yellow") {
console.log("Wait");
} else if (light === "green") {
console.log("Go");
} else {
console.log("Broken light");
}
Go
The final else catches everything that no question matched, such as a light that shows purple. It is a good habit to have one, even if it only prints a warning: a value you did not expect is often the first sign of a bug.
The order of the questions
Because the first true question wins, the order matters whenever the questions overlap. A school portal gives grades by marks: A for 90 and above, B for 75 and above, C for 60 and above. Asked from the top, with the highest band first, it works:
const marks = 82;
if (marks >= 90) {
console.log("A");
} else if (marks >= 75) {
console.log("B");
} else if (marks >= 60) {
console.log("C");
} else {
console.log("Needs work");
}
B
Now the same questions in the opposite order. 82 is at least 60, so the first question is already true, and its block runs. The questions below it are never asked:
const marks = 82;
if (marks >= 60) {
console.log("C");
} else if (marks >= 75) {
console.log("B");
} else if (marks >= 90) {
console.log("A");
}
C
When the bands overlap, as "at least 60" includes everyone with at least 75, ask the narrowest question first.
A choice inside a choice
A block can hold any code, another if included. This is called a nested if. Two nested ifs often say the same as one if with &&:
const age = 15;
if (age >= 13) {
if (age <= 19) {
console.log("teen");
}
}
console.log(age >= 13 && age <= 19);
teen
true
When both questions lead to one action, the && form is shorter and easier to read. Nest only when each level has work of its own to do.
Three traps in a condition
These three slips all run without an error, which is what makes them dangerous. The first is a single = where === was meant:
let x = 0;
if (x = 5) {
console.log("yes", x);
}
yes 5
A single = is not a question. It sets x to 5, and the value of the whole assignment is 5, which is truthy, so the block runs. Worse, x has been changed. Read every = in a condition aloud as "is set to", and the slip stands out.
The second is an if with no braces. JavaScript allows it, but then only the one statement after the condition belongs to the if. Indenting a second line does not make it part of the if:
const paid = false;
if (paid)
console.log("Thank you");
console.log("Receipt sent");
Receipt sent
A receipt was sent for a bill that was never paid. Always write the braces, even for one line, and the question of which lines belong never arises.
The third is => typed where >= was meant. The two characters swapped make an arrow function, which the functions lesson of this track explains. A function is an object, and objects are truthy, so the if runs for any marks at all:
const marks = 40;
if (marks => 90) {
console.log("A grade");
}
A grade
const marks = 40;
console.log(typeof (marks => 90));
function
To remember the order of the characters, read the operator aloud: "greater than or equal to". Greater comes first, so > comes first.
Worked example 7
An electricity board charges ₹3 a unit for the first 100 units of a month, ₹5 a unit for the next 200 units, and ₹7 a unit for every unit above 300. (The rates here are made up for the example; real boards publish their own.) Work out the bill for 350 units.
What we have: the three rates, and 350 units used
What we need: the bill in rupees
The plan: the bill depends on which band the units reach, so ask from the lowest band up, and add each band's share
- Up to 100 units, every unit is at ₹3.
- From 101 to 300, the first 100 units cost 100 × 3, and the rest cost ₹5 each.
- Above 300, the first 100 cost 100 × 3, the next 200 cost 200 × 5, and the rest cost ₹7 each.
const units = 350;
let bill;
if (units <= 100) {
bill = units * 3;
} else if (units <= 300) {
bill = 100 * 3 + (units - 100) * 5;
} else {
bill = 100 * 3 + 200 * 5 + (units - 300) * 7;
}
console.log(bill);
1650
The bill is ₹1650.
Check: 100 × 3 + 200 × 5 + 50 × 7 = 300 + 1000 + 350 = 1650.
A path that fails: charging every unit at the rate of the highest band reached: 350 × 7 = 2450. Slab rates apply each rate only to the units inside its own band.
Worked example 8
A bus company's fare is ₹120. Children under 5 travel free, and children from 5 to 11 pay half. Work out the fare for a child of 7.
What we have: a full fare of 120, two rules for children, and an age of 7
What we need: the child's fare
The plan: start with the full fare, then change it if a rule applies, asking the youngest band first
const age = 7;
let fare = 120;
if (age < 5) {
fare = 0;
} else if (age < 12) {
fare = fare / 2;
}
console.log(fare);
60
- Age 7 is not under 5, so the first block is skipped. It is under 12, so the fare is halved. There is no else: an adult keeps the full fare, which fare already holds.
The child pays ₹60.
Check: half of 120 is 60, and a 4-year-old would pay 0, an 11-year-old 60 and a 12-year-old the full 120.
A path that fails: writing the second question as age <= 11 && age >= 5 and the first as age < 5 in separate ifs, not in one chain. It gives the same answers here, but two separate ifs can both run, and every new rule makes the overlaps harder to see. One chain runs at most one block.
When you are stuck: the wrong block runs
Print the condition itself, just above the if: console.log(marks >= 75);.
Check the order. In a chain, the first true question wins, so put the narrowest question first.
Check every = inside a condition. A question needs ===.
Check the braces. Without them, only one line belongs to the if.
Your turn
const t = 31;
if (t > 35) {
console.log("Very hot");
} else if (t > 25) {
console.log("Warm");
} else {
console.log("Pleasant");
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Warm
- 31 > 35 is false, so the first block is skipped.
- 31 > 25 is true, so Warm is printed.
- The else is skipped, since a question was already true.
It prints Warm.
Rewrite if (x = 10) { ... } so that it asks whether x is 10, without changing x.Tap to reveal
- A single = sets x. The question "is x exactly equal to 10?" needs ===.
let x = 3;
if (x === 10) {
console.log("ten");
} else {
console.log("not ten", x);
}
not ten 3
Write if (x === 10) { ... }; x keeps its value.
A shop gives 10% off bills of ₹1000 or more, and 5% off bills of ₹500 or more. Write a chain that works out the discount on a bill of ₹750.Tap to reveal
- Ask the narrower question first: ₹1000 or more, then ₹500 or more.
const bill = 750;
let discount = 0;
if (bill >= 1000) {
discount = bill * 10 / 100;
} else if (bill >= 500) {
discount = bill * 5 / 100;
}
console.log(discount);
37.5
The discount is ₹37.50: 5% of 750.
Did you know?
Two lines that broke a lock
Missing braces once broke a security check. In February 2014, Adam Langley described a bug in Apple's code for secure connections: two goto fail lines in a row under one if. The first was bound to the if, but the second, despite the indentation, was not conditional at all. The code always jumped past the check, so the signature verification never failed.
Why it fits here: It is the reason for this topic's rule to always write braces: indentation shows what a person meant, braces what the machine does.
There is no else if
JavaScript has no else if keyword. MDN notes that there is no elseif, in one word, in the language: an else if is an else whose one statement happens to be another if. The standard's grammar for an if statement has only if, a condition, a statement, else and a statement. So a chain of else if is a ladder of ifs, each tried only when every one above it was false.
Why it fits here: It explains this topic's rule that the first true question wins: each later if lives inside the else of the one before.
Sources: MDN: if...else; ECMAScript Language Specification: The if Statement
In one line
An if runs its block when the condition is truthy, and an else runs when it is not. In a chain of else if, the first true question wins, so ask the narrowest first. Always write the braces, and never a single = or a => inside a condition.
Choosing a value: the ternary operator
At a glance
At a tea stall the question is short: tea or coffee? The answer is not a series of steps but a single thing to hand over. A program's choice is often like that: not which code to run, but which value to use.
The ternary operator, condition ? a : b, gives a when the condition is truthy and b when it is not. Use it for a choice between two values, even inside a template literal. For steps, or for more than two answers, use an if.
Take a guess: What does the ternary operator give back: a block of code, or a value?
At a tea stall the question is short: "Tea or coffee?" The answer is not a series of steps but a single thing to hand over. Often a program's choice is like that too: not which code to run, but which value to use. For that, there is a shorter form than if.
The operator condition ? a : b, which gives a when the condition is truthy and b when it is not. Read it aloud as "if condition, then a, otherwise b". It is called ternary because it is the only operator in JavaScript that takes three values.
const total = 650;
const delivery = total >= 499 ? 0 : 40;
console.log(delivery);
0
Read the second line aloud: "delivery is set to: if total is at least 499, then 0, otherwise 40". 650 is at least 499, so delivery is 0. With an if, the same choice takes five lines and needs a let, because the name is assigned inside the blocks. The ternary gives the value straight to a const.
Inside a template literal
Because a ternary gives a value, it can go anywhere a value can, including a gap in a template literal. This is how an app writes 1 item but 3 items:
const n = 1;
const m = 3;
console.log(`${n} ${n === 1 ? "item" : "items"}`, `${m} ${m === 1 ? "item" : "items"}`);
1 item 3 items
const n = 0;
console.log(`${n} ${n === 1 ? "item" : "items"}`);
0 items
Notice that the question is n === 1, not n > 1. English says 0 items, not 0 item, so the singular is the special case, and the question should name it.
More examples
const x = 7;
console.log(x % 2 === 0 ? "even" : "odd");
odd
const isMember = true;
const price = 200;
console.log(isMember ? price * 0.9 : price);
180
const name = "Asha";
console.log(name === "Asha" ? "Welcome back" : "Hello, stranger");
Welcome back
When not to use it
A ternary can hold another ternary, and the result works:
const marks = 33;
const result = marks >= 90 ? "A" : marks >= 75 ? "B" : marks >= 33 ? "Pass" : "Try again";
console.log(result);
Pass
But it is hard to read, and harder still to change. Once a choice has more than two answers, an if chain says the same thing in a way that is easier to read. A good rule: use a ternary for a choice between two values, and an if for anything more, or for any choice that runs steps rather than giving a value.
| Use | When | Example |
|---|---|---|
| a ternary | choosing between two values | n === 1 ? "item" : "items" |
| an if | running different steps, or more than two answers | the grade chain of the last section |
Worked example 9
A food app shows the delivery line as Delivery: free when the order is ₹499 or more, and Delivery: ₹40 otherwise. Write the line for an order of ₹350.
What we have: a total of 350, a free-delivery limit of 499 and a fee of 40
What we need: the text Delivery: ₹40
The plan: work out the fee with one ternary, then choose the words with a second ternary inside the template literal
const total = 350;
const fee = total >= 499 ? 0 : 40;
console.log(`Delivery: ${fee === 0 ? "free" : "₹" + fee}`);
Delivery: ₹40
- The first ternary chooses a number. The second chooses the words, and joins the ₹ sign to the fee only when there is one.
It prints Delivery: ₹40.
Check: with a total of 650 the fee is 0, and the line reads Delivery: free.
A path that fails: putting the whole rule into one line: `Delivery: ${total >= 499 ? "free" : "₹" + 40}`. It works today, but the fee is now written in a sentence, so when the fee changes it must be found and changed there too. Keeping the number in a name of its own makes the rule easy to change.
When you are stuck: a ternary gives the wrong value
Read it aloud: "if ..., then ..., otherwise ...". The value for true comes first, straight after the ?.
Print the condition on its own to see its true or false.
If the line holds more than one ? and :, rewrite it as an if chain.
Inside a template literal, check that the whole ternary sits inside the gap's braces.
Your turn
const temp = 18;
console.log(temp > 25 ? "Fan on" : "Fan off", temp < 20 ? "Sweater" : "Shirt");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Fan off Sweater
- 18 > 25 is false, so the second value: Fan off.
- 18 < 20 is true, so the first value: Sweater.
It prints Fan off Sweater.
Write a ternary that gives "pass" for marks of 33 or more and "fail" otherwise, and test it with 33 and 32.Tap to reveal
let marks = 33;
console.log(marks >= 33 ? "pass" : "fail");
marks = 32;
console.log(marks >= 33 ? "pass" : "fail");
pass
fail
marks >= 33 ? "pass" : "fail" gives pass for 33 and fail for 32.
Turn this if into a single line with a ternary: let label; if (count === 1) { label = "seat"; } else { label = "seats"; }Tap to reveal
- The if only chooses between two values for label, so a ternary fits, and label can be a const.
const count = 2;
const label = count === 1 ? "seat" : "seats";
console.log(count, label);
2 seats
const label = count === 1 ? "seat" : "seats";
Did you know?
The only three-part operator
Every other JavaScript operator works on one value or two. The ternary is the only JavaScript operator that takes three operands: a condition, then a question mark and a value for yes, then a colon and a value for no. The standard's grammar spells the shape out as a short-circuit expression, a question mark, an expression, a colon and another expression.
Why it fits here: It explains the name of this topic's operator: it is the one that takes three parts, which is why it can choose between two values.
Sources: MDN: Conditional (ternary) operator; ECMAScript Language Specification: Conditional Operator
Older than C
Choosing a value with a condition is older than C and JavaScript. The construct first appeared in CPL in 1963, written a → b, c, with an arrow for the question and a comma between the two answers. Many languages since have their own spelling, often if a then b else c. JavaScript uses the question mark and colon of the C family.
Why it fits here: It shows that this topic's operator answers an old need: picking a value, rather than running steps, by a condition.
Sources: Wikipedia: Ternary conditional operator; MDN: Conditional (ternary) operator
In one line
The ternary condition ? a : b gives a value: a when the condition is truthy, b otherwise. Use it for a choice between two values, even inside a template literal, and use an if for steps or for more than two answers.
Choosing a path: switch
At a glance
A lift has a button for each floor. Press 3, and it goes to the third floor; it does not ask whether 3 is more than 2. It matches the button against a fixed list, and when a choice works like that, JavaScript has a statement made for it.
A switch compares one value with each case, using ===, and runs from the first match until a break. Leave a break out, and it falls through into the next case. Group empty cases on purpose, end the rest with break, and keep a default.
Take a guess: What happens when a case has no break at its end?
A lift has a button for each floor. Press 3, and it goes to the third floor; press 5, and it goes to the fifth. It does not ask "is it more than 2? is it less than 4?". It matches the button against a fixed list. When a choice works like that, one value compared against a list of exact answers, JavaScript has a statement made for it.
A statement that compares one value against a list of case values, using ===, and runs the code from the first case that matches. break ends the switch, and default runs when no case matches.
const day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
Wednesday
Read it from the top. The value in brackets is day, which is 3. JavaScript compares it with each case in turn: 1 is not 3, 2 is not 3, 3 is 3. It runs the lines after case 3, prints Wednesday, and reaches break, which jumps straight past the end of the switch.
The missing break
Here is the most famous trap of switch. Without a break, JavaScript does not stop at the end of a case. It carries on into the next case's lines, and the next, whether they match or not. This is called fall-through.
const signal = "yellow";
switch (signal) {
case "red":
console.log("Stop");
case "yellow":
console.log("Get ready");
case "green":
console.log("Go");
}
Get ready
Go
The signal was yellow, so the switch started at case "yellow", and printed Get ready. With no break, it fell through into case "green" and printed Go as well. A driver reading this program would set off on a yellow light. End every case with a break, unless you mean it to fall through.
Falling through on purpose
Sometimes fall-through is exactly what you want: when several values share one action. Put the cases one under another with nothing between them:
const day = "Sunday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
Weekend
Sunday did not match Saturday, but it matched Sunday, and the shared lines ran. Saturday would have matched first, found no lines, and fallen through into the same lines. An empty case that falls through is a common and safe pattern; a case with lines that falls through is almost always a bug.
switch uses ===
switch compares with ===, so the type must match as well as the value. A choice that arrives from a page as the string "1" matches no case written as the number 1:
const choice = "1";
switch (choice) {
case 1:
console.log("one");
break;
default:
console.log("no match");
}
no match
Convert the value before the switch, and the cases match:
const choice = "2";
switch (Number(choice)) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
default:
console.log("no match");
}
two
switch or if?
| Use | When | Example |
|---|---|---|
switch | one value, compared against a list of exact answers | a menu number, a day's name, a signal's colour |
if with else if | ranges, or questions about different values | marks of 75 or more, an age under 12, a ticket and an age together |
A switch compares each case with === against one value, so it suits exact answers, not ranges. A pattern written switch (true) can bend it to ranges, but an if chain says the same thing more plainly.
Worked example 10
A tea stall's ordering screen numbers its drinks: 1 for tea at ₹15, 2 for coffee at ₹20 and 3 for lassi at ₹30. Any other number is not on the menu. Write the switch for a customer who presses 2.
What we have: the number pressed, 2, and three drinks with their prices
What we need: the line for the drink chosen, or a message for a number not on the menu
The plan: switch on the number, with a case and a break for each drink, and a default for everything else
const item = 2;
switch (item) {
case 1:
console.log("Tea, ₹15");
break;
case 2:
console.log("Coffee, ₹20");
break;
case 3:
console.log("Lassi, ₹30");
break;
default:
console.log("Not on the menu");
}
Coffee, ₹20
- The value 2 matched case 2, and the break kept the switch from falling into the lassi.
It prints Coffee, ₹20.
Check: pressing 4 matches no case, so the default prints Not on the menu.
A path that fails: leaving out the break after the coffee. The customer who chose coffee is then shown Lassi, ₹30 on the next line as well, and may well be charged for both.
When you are stuck: a switch runs too much, or nothing
If it runs the lines of several cases, look for a missing break.
If it matches nothing, check the type of the value: a string never matches a case written as a number. Print typeof of the value.
Check for a default. Without one, a value that matches nothing runs nothing, silently.
If you need a range, such as marks of 75 or more, use an if chain instead.
Your turn
const level = "B";
switch (level) {
case "A":
console.log("Top");
case "B":
console.log("Good");
case "C":
console.log("Fair");
break;
default:
console.log("Unknown");
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Good
Fair
- The value B matches case B, so Good is printed.
- There is no break after Good, so it falls through to case C and prints Fair.
- The break after Fair ends the switch before the default.
It prints Good, then Fair.
Write a switch that prints Weekend for "Saturday" and "Sunday", and Weekday for any other day, then test it with "Monday".Tap to reveal
- Group the two weekend cases with nothing between them, so they share one action.
const day = "Monday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
Weekday
Monday matches no case, so the default prints Weekday.
A switch on a value read from a page never matches its cases 1, 2 and 3, and always runs its default. What is the most likely cause?Tap to reveal
- A value from a page arrives as a string, such as "2".
- switch compares with ===, and "2" === 2 is false.
- Convert it first:
switch (Number(value)).
The value is a string; convert it with Number(...) before the switch.
Did you know?
Pride and revulsion
Fall-through has a famous trick. In November 1983, Tom Duff, then working for Lucasfilm, mailed a way of unrolling a loop by interleaving a do-while loop and a switch statement, so that the switch falls into the middle of the loop. He wrote: "Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this discovery."
Why it fits here: It shows how much fall-through can do, and why this topic asks for a break after every case that should stop.
Sources: Wikipedia: Duff's device; Tom Duff's message of 1983 (copy kept by Russ Cox)
A default anywhere
The default of a switch does not have to come last. MDN notes that by convention the default clause is the last one, but it does not need to be so. The standard's grammar allows case clauses both before and after the default. When no case matches, the switch moves to the default wherever it stands and runs the statements that follow it. From there it falls through, like any other case, until a break.
Why it fits here: It is one more reason for this topic's break in every case: an early default would otherwise run on into the cases below it.
Sources: MDN: switch; ECMAScript Language Specification: The switch Statement
In one line
A switch compares one value with each case, using ===, and runs from the first match until a break. Leave a break out and it falls through into the next case. Group empty cases on purpose, end the rest with break, and keep a default.
Where it is used
Every program that reacts to anything makes choices. Here is where each idea of this lesson shows up in real work.
| What you learned | Where it is used | A real example |
|---|---|---|
=== and !== | checking an answer, a password, a code | an OTP screen compares the six digits typed with the six digits sent |
<, >, <=, >= | limits, thresholds and offers | free delivery on orders of ₹499 or more |
| comparing strings | sorting names, searching | a contacts list put in order; a search that ignores capitals |
&& and || | rules with more than one part | a loan form checks an age over 21 and an income above a limit |
?. and && as guards | data that may be missing | a profile page that shows the city only if the user filled one in |
?? and || for defaults | settings and empty fields | a player's score of 0 kept as 0, an empty nickname replaced by the name |
if, else if, else | rules with bands | income tax slabs, electricity slabs, grade bands on a results portal |
| the ternary | small choices in text | 1 item, 3 items; Delivery: free |
switch | menus and fixed choices | an IVR phone menu: press 1 for Hindi, 2 for English |
Mistakes and debugging
Most slips in conditions give no error at all: the program runs, and quietly takes the wrong path. That is why the debugging habit of this lesson is to print the condition itself. Every output below is the real one, from the code shown.
1. A single = in a condition
let x = 0;
if (x = 5) {
console.log("yes", x);
}
yes 5
No error: x is set to 5, which is truthy. The fix: if (x === 5).
2. => where >= was meant
const marks = 40;
if (marks => 90) {
console.log("A grade");
}
A grade
No error: marks => 90 is a function, and functions are truthy. The fix: marks >= 90, greater first.
3. A chained comparison
console.log(1 < 20 < 10);
true
No error: 1 < 20 is true, and true < 10 is true. The fix: x > 1 && x < 10.
4. Numbers compared as text
console.log("1200" < "200");
true
No error: two strings are compared character by character. The fix: convert the readings with Number(...) as they arrive.
5. A real 0 treated as missing
const reading = 0;
console.log(reading && reading < 200, reading || "missing");
0 missing
No error: 0 is falsy. The fix: ask reading !== undefined, or use reading ?? "missing".
6. A missing break
const signal = "yellow";
switch (signal) {
case "yellow":
console.log("Get ready");
case "green":
console.log("Go");
}
Get ready
Go
No error: the yellow case falls through into green. The fix: end each case with break;.
7. An if with no braces
const paid = false;
if (paid)
console.log("Thank you");
console.log("Receipt sent");
Receipt sent
No error: only the first line after the condition belongs to the if. The fix: always write the braces.
8. A bracket left open
const marks = 95;
if (marks > 90 {
console.log("A");
}
Uncaught SyntaxError: Unexpected token '{'
The fix: close the condition's round bracket before the curly one: if (marks > 90) {.
9. else after a line with no semicolon
const a = 5;
if (a === 5) console.log("five") else console.log("other");
Uncaught SyntaxError: Unexpected token 'else'
The fix: use braces for each branch, as this lesson does everywhere. They show where each branch ends, and the message never appears. A semicolon before the else also ends the first branch, but braces are easier to read.
10. Reading from null
const user = null;
console.log(user.name);
Uncaught TypeError: Cannot read properties of null (reading 'name')
at line 2
The fix: guard the step: user?.name gives undefined, and user && user.name gives null, instead of an error.
The debugging corner: print the question
When a program takes the wrong path, print the condition just above the if: console.log(reading, typeof reading, reading < 200);. You see the value, its type and the exact true or false the program acted on. Nine times out of ten, one of the three is not what you expected. In the Sources panel of the DevTools step, a breakpoint on the if shows the same three things without any printing.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
// compare with === and !==; < and > compare strings character by character
console.log(5 === "5", "2" > "12", Number("1200") < 200, NaN === NaN);
// && both, || either, ! not; && and || give back one of their values
console.log(true && false, true || false, !true, "" || "Guest", 0 ?? 10);
// falsy: false 0 -0 0n "" null undefined NaN; everything else is truthy
console.log(Boolean("0"), Boolean(0), Boolean([]));
// if, else if, else: the first true question wins
const marks = 82;
if (marks >= 90) {
console.log("A");
} else if (marks >= 75) {
console.log("B");
} else {
console.log("C");
}
// the ternary picks a value; switch matches one value with ===
const n = 3;
console.log(`${n} ${n === 1 ? "item" : "items"}`);
switch (n) {
case 3:
console.log("three");
break;
default:
console.log("other");
}
false true false false
false true false Guest 0
true false true
B
3 items
three
| When you see | It means | Look at |
|---|---|---|
| a condition that is always true | a single = or a => inside it | read each operator aloud |
| a number range that lets everything in | a chained comparison such as 1 < x < 10 | two questions joined with && |
| 1200 counted as less than 200 | two strings compared as text | convert with Number(...) |
| a real 0 treated as missing | 0 is falsy | x !== undefined, or ?? |
| several cases of a switch running | a missing break | the end of each case |
| a switch that matches nothing | a string compared with number cases | switch (Number(value)) |
SyntaxError: Unexpected token 'else' | a branch with no braces before an else | braces on every branch |
TypeError: Cannot read properties of null | a step that reads from null | ?. or an && guard |
The story: Under 200 paces, and only then
You read each question that the script asks of its readings. One asked whether there was a reading at all, and in the thickest fog the glass reads 0, which that question took for no reading. Another compared the readings as text, character by character, so 1200 paces came out smaller than 200.
You turn the readings into numbers as they arrive, and ask about a missing reading in so many words. The horn booms out over the water, and somewhere in the white a ship's bell answers.
Master Verge listens until the bell fades. "Now it decides," he says. "Next, teach it to do one job whenever it is asked."
Reagents gathered: ===, &&, ||, truthy and falsy, if, switch.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)