LOGBOOK

HELP

Quiz Entry - updated: 2026.07.05

What is type coercion in JavaScript, and why can it be confusing?

Type coercion is JavaScript automatically converting one type into another during an operation — and it's confusing because + sometimes adds and sometimes joins text.

Because JavaScript is dynamically typed, when an operation mixes types it doesn't just give up — it quietly converts ("coerces") a value into the type it needs. This implicit conversion is convenient but can produce surprising results:

let num = 1;    // a Number
let str = '2';  // a String

let result1 = str - num;   // 4? No: 1. The string '2' → number 2, then 2 - 1
let result2 = num + str;   // 3? No: '12'. The number 1 → string '1', then '1' + '2'

The root of the confusion is that the + operator is ambiguous:

  • With two numbers, it adds them.
  • If either side is a string, it concatenates — converting the number to a string and gluing them together.

Other arithmetic operators have no such ambiguity. Subtraction (-), *, / only make sense for numbers, so they always try numeric conversion.

To stay in control, convert explicitly with parseInt() or parseFloat() when you want a number, and use === (strict equality) for comparisons so that no hidden coercion happens behind your back.

Go deeper:

From Quiz: WEBT / Introduction to JavaScript | Updated: Jul 05, 2026