liveBook · Manning

Type coercion

As explained in Secrets of the JavaScript Ninja, Third Edition

The implicit conversion of a value from one type to another during an operation or expression evaluation.

Type coercion is JavaScript’s implicit conversion of values during an operation. Instead of rejecting incompatible operands, JavaScript may convert them: `1 + "2"` produces the string `"12"`. This can make results surprising, so knowing how to avoid unintended coercion is more useful than memorizing every rule. section 1.3.1 section 2.1

Surprising results

`[] + {}` produces `"[object Object]"`, while `[] + ""` produces `""`. These examples show why JavaScript’s flexible conversions can lead to unexpected values. section 1.3.1

Coercion is distinct from dynamic typing: dynamic typing means types are enforced at runtime, while coercion converts values implicitly. TypeScript retains JavaScript’s runtime behavior, but its type checker can predict that `1 + "2"` produces a string and flag its use where a string is not expected. section 2.1 section 2.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines implicit conversion and demonstrates string and array-object outcomes, but does not enumerate coercion rules.
Examples
Shows `1 + "2"`, `[] + {}`, and `[] + ""` to demonstrate unexpected conversion results.
What you can do after
Understand when JavaScript converts operands implicitly and how TypeScript can flag incompatible predicted results.
How it connects
Distinguishes implicit coercion from dynamic typing and connects it to TypeScript’s static type checking.

Also explained in

Compare how 2 books explain type coercion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.