VCF

Unit 4 · Thinking like a programmer

Why "2" + 2 is "22" in JavaScript

+ adds two numbers but joins text. If either side is a string, JavaScript turns the other side into text too, so "2" + 2 is "22". Convert each value with Number() before adding.

The mix-up

What people often think

“+ always means add.”

What the tutor says

+ adds two numbers, but it joins text. With a string on either side, you get joined text: "22".

What would "cat" + "dog" give?

How it works

Quotes make a value text, even when it contains only digits. "42" is a string, like a phone number written on paper; 42 is a number you can do maths with.

Form fields always hand you text, whatever the person typed. Wrapping the whole sum in Number() comes too late: Number("2" + "3") joins first and gives 23. Convert each value on its own, then add.

JavaScript does not refuse to mix types; it quietly converts one side. That is why these bugs run without an error and are easy to miss.

Side by side

The mix-upJavaScript
const a = input1.value;  // "2"
const b = input2.value;  // "3"
Number(a + b);           // 23
Joined, then converted.
What worksJavaScript
Number(a) + Number(b);   // 5
Converted, then added.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “"42" is a number because it is made of digits.”

    The quotes win. "42" is text that happens to contain digits, like a phone number written on paper.

  • “Wrapping the whole sum in Number() fixes it.”

    That joins the text first, making "23", then converts it to 23. Convert each box on its own, then add.

  • “Taking the quotes off the inputs solves it.”

    You do not control what the form sends, and it always sends text. Leave the inputs alone and convert them.

  • “JavaScript refuses to mix text and numbers.”

    It does not refuse. It quietly converts one side to match, which is why these bugs are easy to miss.

Practise it with a tutor watching

Types: text, numbers and yes/no

Tell strings, numbers, booleans and null apart, and convert text to numbers on purpose.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.