JavaScript Type coercion

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

Type coercion is automatic conversion between types. == coerces before comparing. + prefers string concatenation if either side is a string. Prefer === and explicit conversions in most code.

JavaScript Syntax

JavaScript
console.log(1 + "2");
console.log("5" - 2);
console.log(1 == "1");
console.log(1 === "1");
Try it Editor

How It Works

  1. +. String wins → "12".
  2. -. Numeric → 3.
  3. == vs ===. Loose vs strict.

Examples

Example 1 — To boolean

Truthy/falsy rules.

JavaScript
console.log(!!"x");
console.log(!!0);
Try it Editor

How It Works

  1. !! coerces to boolean.

Example 2 — Explicit Number

Avoid surprises.

JavaScript
console.log(Number("  8 "));
console.log(Number("x"));
Try it Editor

How It Works

  1. Explicit conversion is clearer.

Example 3 — Objects

valueOf / toString.

JavaScript
console.log(String({}));
console.log(Number([]));
Try it Editor

How It Works

  1. Default object stringification.
  2. Empty array becomes 0.

Frequently Asked Questions

Use ===, explicit Number/String/Boolean, and ?? instead of || for defaults.
No—template strings and numeric operators often coerce intentionally. Be explicit when clarity matters.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful