Priya’s age came through the sign-up script as "9", a string. Whatever a volunteer types at the terminal arrives as text, but the tracker’s sums and age checks need numbers.
In this lesson, you’ll find a silent bug that this text causes and see why one operator hides it. Then you’ll write two input helpers that convert each value once, where it comes in, and throw a library error when the text isn’t a usable whole number. Start with a family’s donation.
Add Copies the Volunteers Typed
A family has donated three more wooden train sets. The volunteers record donations with a script that uses the readline recipe, where await rl.question() waits for the volunteer and hands back what they typed. Reuse this recipe as it is for now. How await works is for later.
Each new copy needs two labels, one for the box and one for the train, and the shelf already holds one train set. Save the script as add-copies.js:
add-copies.js
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
const rl = createInterface({ input: stdin, output: stdout });
const copies = await rl.question("Train sets to add: ");
rl.close();
console.log(`Labels to print: ${copies * 2}`);
console.log(`Train sets on the shelf: ${copies + 1}`);
Run it with node add-copies.js and type 3 at the prompt. Before you press Enter, predict both lines the script prints.
The labels are right, and the shelf total is wrong:
$ node add-copies.js
Train sets to add: 3
Labels to print: 6
Train sets on the shelf: 31
You may have seen a total like this before and fixed it with Number(). What’s new here is that the labels line looked right, so copies seemed to be a number. Step into the REPL to see what JavaScript did with it:
> const copies = "3";
undefined
> typeof copies
'string'
> copies * 2
6
> copies - 1
2
> copies + 1
'31'
> 0 + "10"
'010'
copies stays a string the whole time. * and - convert "3" to a number for each calculation. This silent conversion is called type coercion.
However, + also joins strings. When either side is a string, + converts the other side to a string and joins them, so "3" + 1 is "31". The last line shows the same rule inside a running total: start at 0, add the text "10", and you get "010".
So a working * doesn’t tell you a value is a number. Don’t let each operator decide. Convert the text once, where it enters the program, and use the number everywhere after that.