JavaScript traps · Chapter 2 of 16
== and NaN
Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Everyday traps
- 3 tasks
- JavaScript
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
The lesson
By the end of this case
You can tell NaN and loose equality from their symptoms, make a bad quantity box happen on purpose, check a number the safe way, and guard it with a test that tries the awkward inputs, not only the easy ones.
The ticket
TAP-314: Receipts that say ₹NaN, and free bun maska. Assigned to you by Kabir. Priority: medium. Since: the new quantity box.
Anjali, in the design channel at 11:15 am: "A customer sent me a screenshot of her receipt. It says Total: ₹NaN. She had typed 'two' in the quantity box instead of 2. And yesterday someone left the box empty on a bun maska, the kitchen made it, and the receipt charged ₹0 for it. The box is supposed to say Enter a whole number of cups."
The cart log for both orders:
11:02:47.115 cart cart 5120: NaN x masala chai
18:40:09.502 cart cart 5127: 2 x cutting chai
18:40:12.881 cart cart 5127: 0 x bun maska
Kabir: "The quantity box went from a number picker to a plain text box last week, so addLine now gets whatever people type, as a string. There is a check in there that is meant to refuse junk, and it has never refused anything. Reproduce it, fix it, then make sure it never comes back. You are in cart.js."
What Number makes of a text box
A text box always gives you a string. Number turns it into a number, and it is more generous than you might think. Here is the kitchen's box for litres of milk delivered:
for (const typed of ['12', ' 8 ', 'twelve', '', ' ', '2.5'])
console.log(JSON.stringify(typed), Number(typed));
"12" 12
" 8 " 8
"twelve" NaN
"" 0
" " 0
"2.5" 2.5
Spaces around a number are fine. A word gives NaN ("not a number"). And an empty box, or one full of spaces, gives 0, not an error.
NaN equals nothing
NaN is the one value in JavaScript that is not equal to itself, so no comparison with it is ever true:
const litres = Number('twelve');
console.log(litres === NaN, litres == NaN, NaN === NaN);
console.log(litres > 0, litres < 0, litres + 5);
console.log(`Milk: ${litres * 60} rupees`);
false false false
false false NaN
Milk: NaN rupees
So a check written as "is it NaN?" with === never holds, a check like "is it below zero?" lets NaN through too, and NaN spreads through every sum it touches until it lands on a screen. Nothing throws on the way.
The empty box is the same story told by ==. Loose equality turns both sides into numbers first, and the empty string becomes 0:
console.log('' == 0, ' ' == 0, '0' == 0, '' == '0');
console.log('' === 0, Number('') === 0);
true true true false
false true
=== never converts, which is why it is the one to use. But here the box's text has already gone through Number, so the empty box is a real 0 before any comparison happens.
Two isNaN functions
There are two, and they disagree. The global isNaN turns its argument into a number first, so the empty box is "a number". Number.isNaN is true only for the value NaN itself. Number.isInteger is true only for a whole number, and false for NaN:
for (const typed of ['twelve', '', ' ', '2.5'])
console.log(JSON.stringify(typed), isNaN(typed), Number.isNaN(Number(typed)), Number.isInteger(Number(typed)));
"twelve" true true false
"" false false true
" " false false true
"2.5" false false false
Look at the empty box: neither NaN check refuses it, because by then it is 0. Deciding what counts as a quantity is your job, not isNaN's.
A test for a throw
New in the guard: checking that a call throws. Wrap the call in an arrow function so vitest can run it and catch the error: expect(() => receiveMilk('twelve')).toThrow('Enter litres'). A guard for an input check should try the awkward inputs (a word, an empty box, spaces, a decimal, zero) and one good input, or a check that refuses everything would pass it.
Your turn
Three tasks, one file each. In repro.js, put 'two' in the quantity box on purpose and resolve to the receipt's total, and run it with node repro.js in the case's folder. In cart.js, make addLine refuse anything that is not a whole number of 1 or more. In cart.test.js, write the guard: the check runs it beside the original code, the fix and a wrong fix that uses the global isNaN. Then answer Kabir's interview question at the bottom of the case.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
repro.js: put 'two' in the quantity box on purpose
Write reproduce() in repro.js. Make an empty cart, an object { id, lines: [] } with any id, and add 'two' masala chai to it with addLine(cart, 'masala chai', 'two') from cart.js, the way the quantity box would. Resolve to totalText(cart). If addLine throws, catch the error and resolve to its message instead.
The check runs your reproduce() twice: beside the original cart.js it must resolve to 'Total: ₹NaN' (the receipt from the ticket), and beside a fixed cart.js it must resolve to 'Enter a whole number of cups', the message the fixed addLine throws. So it must really call addLine with 'two' and catch what it throws. No real waiting: reproduce() must finish within 2 seconds.
- Task 2
cart.js: refuse a quantity that is not a number
Fix addLine(cart, item, qtyText) in cart.js. qtyText is the text from the quantity box. It must refuse every quantity that is not a whole number of 1 or more by throwing Error('Enter a whole number of cups') and adding no line: 'two', '', ' ', '1.5', '-1' and '0' are all refused. '3' and ' 2 ' are accepted: addLine adds the line { item, qty, amount } with qty as the number 3 or 2 and amount as qty times the item's price, logs cart <id>: <qty> x <item> and returns the line.
Keep PRICES, totalText, the error's text and the log line as they are. The check uses its own carts and items and tries every quantity above; a fix that refuses words but lets the empty box through is still wrong.
- Task 3
cart.test.js: a test that would have caught it
Write a vitest test file, cart.test.js, that would have caught this bug. The check runs your file three times: beside the original cart.js, where at least one test must fail; beside the fixed cart.js, where every test must pass; and beside a wrong fix that refuses quantities with the global isNaN, which lets an empty box through as 0, where at least one test must fail.
So test both sides: 'two' and an empty box are refused with the error 'Enter a whole number of cups', and a real quantity such as '3' or ' 2 ' is added with qty as a number. Each test must finish within 3 seconds.
What you will learn
- repro.js: put 'two' in the quantity box on purpose
- cart.js: refuse a quantity that is not a number
- cart.test.js: a test that would have caught it
More in Everyday traps
Build "== and NaN" yourself
Tapri runs on JavaScript, and Kabir, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.