25 min·beginner

Lesson 7

Conversion & coercion

Build a practical mental model for conversion & coercion and use it in working JavaScript.

By the end, you will be able to…

  • Explain conversion & coercion in your own words
  • Use conversion & coercion in a small program
  • Recognize and debug a common failure mode

Build the mental model

JavaScript will silently convert types to make an operation succeed — + prefers strings, - and * prefer numbers. Explicit conversion with Number(), String(), and Boolean() makes your intent visible instead of relying on this implicit behavior.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: "51" 4 5

Why this matters

Silent coercion is one of the most common sources of 'why is this NaN' bugs, especially with values coming from form inputs or APIs.

Real-world example

A shopping cart adding a text-input quantity to a price without Number() will concatenate instead of calculating a total.

Common mistakes

  • Adding a string and a number and expecting numeric addition
  • Not converting form input values before doing math on them
  • Assuming Boolean("false") is false (it's true — any non-empty string is truthy)

Try it yourself

Challenge

Fix the total calculator so it adds numbers instead of concatenating strings.

Practice

Knowledge check

What does "5" + 1 evaluate to?

Summary

Prefer explicit conversion (Number(), String(), Boolean()) over relying on implicit coercion.