Skip to the workspace
Pebellslearn by building
Type Casting  ›  Lesson

Conversion vs Coercion

Type Casting 12 min

javascript / Conversion vs Coercion

Explore each scene at your own pace.

01 · Conversion vs Coercion

Conversion vs Coercion

Conversion vs Coercion

Explicit conversion asks for another type directly. Coercion is conversion performed by an operation’s rules.

Make the data boundary visible instead of hoping an operator guesses your intent.

See the mechanism

Walk through the modelConversion vs CoercionAuthored snapshots of the example; use Run below to test the code.
inputstring "4"
Form-like input often arrives as text.
1 of 3

Follow one example

javascript

Number(input) explicitly requests numeric conversion, so addition gives 5. With a string operand, + joins text and produces "41". Subtraction requires numeric operands and coerces this string to a number, producing 3. These are different rules, not evidence that input permanently changed type.

Predict, change and check

Predict: What does typeof input report after all three calculations?

Test your explanation: Print typeof input at the end. Then replace the input with "four" and observe where NaN appears; failed conversion needs validation rather than another arithmetic operation.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Make the boundary visible

An explicit Number(text) call makes a conversion visible in code. An operator such as + or == can invoke implicit conversion as part of its own rules. Explicit conversion is easier to review but still needs validation: Number('') returns 0, which may not mean 'missing input' for your product.

Object-to-primitive conversion can involve Symbol.toPrimitive or methods such as valueOf and toString. Therefore an operator is not always a harmless formatting step. Keep data normalization near the boundary where input enters the application and keep that policy separate from display formatting.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.