JavaScript Implicit Coercion in Expressions
Quick answer
Coercion is a conversion performed as part of evaluating an operation, without an explicit conversion call. The operator determines how operands are interpreted. The same text can behave differently under addition and subtraction.
How it works
For the primitive operands used here, + concatenates when either operand is a string; otherwise it performs numeric addition subject to numeric type rules. Subtraction and multiplication convert these operands to numeric values. Explicit conversion at input boundaries reduces surprises. Strict equality (===) does not perform the coercion done by loose equality; the next chapter expands comparison algorithms.
console.log("6" + 2);console.log("6" - 2);console.log("6" * 2);Expected output in Node.js:
62412Plus selects concatenation; subtraction and multiplication use numeric conversion.
const quantity = "3";const price = "8";console.log(Number(quantity) + Number(price));console.log(quantity === 3);Expected output in Node.js:
11falseThe explicit conversion controls addition; the comparison uses original text.
Common mistakes
When receiving text from a form, do not add a number to it assuming numeric addition. State the expected input type and conversion policy. Object-to-primitive conversion introduces additional rules and is covered in the advanced chapters.
Practice
Given two numeric text values joined in a single input record, return their numeric sum rather than their concatenation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Implicit Coercion in Expressions — Knowledge Check
Apply the taught concept and reason about the result.
What does "5" + 3 produce?
What does "5" - 3 produce?
What does "4" * 2 produce?
What does "3" === 3 evaluate to?
What is a clear way to add two valid numeric strings numerically?