W3Newbie
  • HTML Tutorial
  • CSS Tutorial
  • Web Dev
    • VS Code Tutorial
    • Command Line Tutorial
    • Git Tutorial
    • Github Tutorial
    • Sass Tutorial
  • Courses
  • Resources
  • Tutorials
  • Click to open the search input field Click to open the search input field Search
  • Menu Menu

JavaScript Type Coercion

Home » JavaScript Tutorial » JavaScript Introduction » JavaScript Type Coercion

Type Coercion is JavaScript’s automatic or implicit process of converting a value from one data type to another (e.g., converting a String to a Number, or a Boolean to a String).

While the Operators lesson introduced when this happens (like when using == or + on different types), this lesson explains how the engine performs those conversions and, critically, how to avoid unpredictable behavior.

Implicit Coercion (Automatic)

Implicit Coercion is the process where JavaScript automatically changes the type of an operand to make an operation possible. This is the source of much confusion in JavaScript.

Coercion by Operators

The type of coercion performed depends heavily on the operator being used:

OperatorTarget TypeExampleProcessResult
+ (Addition)String or Number“5” + 5If any operand is a string, the other is converted to a string.“55” (String)
– (Subtraction)Number“5” – 2Always attempts to convert both operands to numbers.3 (Number)
! (Logical NOT)Boolean!”hello”Converts the operand to a boolean (true), then inverts it.false (Boolean)
== (Loose Equality)Common Type“1” == trueConverts both operands to a common type (both become 1).true (Boolean)
const addTest = "5" + 5;
console.log(addTest); // Output: 55
console.log(typeof addTest); // Output: string
console.log("5" + 5 + 10); // Output: 5510

const subtractTest = "5" - 2
console.log(subtractTest); // Output: 3
console.log(typeof subtractTest); // Output: number
console.log("5" - 2 + 10); // Output: 13

const notTest = !"test"
console.log(notTest); // Output: false
console.log(typeof notTest); // Output: boolean

const looseEquality = ("1" == true); // Boolean converted to number (1)
console.log(looseEquality); // Output: true
// Strict equality === would make it false (recommended).
JavaScript

Explicit Coercion (Manually Done On Purpose)

Explicit Coercion is the deliberate, predictable conversion of types using built-in JavaScript functions. This is always the recommended way to handle type conversion, as it leaves no room for ambiguity.

Target TypeConversion FunctionDescriptionExampleResult
StringString(value) or value.toString()Converts any value to its string representation. (value.toString() is a method called on the variable.)String(99)“99”
NumberNumber(value) or parseInt(value)Converts the value into a number. parseInt() is used specifically for parsing integers from strings.Number(“50”)50
BooleanBoolean(value)Converts the value to a pure true or false. The 6 Falsy Values are: false, 0, null, undefined, NaN, and "" (empty string).Boolean(1)true
console.log("\n---String() Example---");

const typeToString = String(44);
console.log(typeToString); // Output: 44 (string)
console.log(typeof typeToString); // Output: string
//Alternative method
console.log(typeToString.toString()); // Output: 44 (string)

console.log("\n---Number() Example---");

console.log(Number(true)); // Output: 1
console.log(Number("1")); // Output: 1
console.log(Number(false)); // Output: 0
console.log(Number([])); // Output: 0
console.log(Number("test")); // Output: NaN
console.log(Number(undefined)); // Output: NaN
console.log(Number({})); // Output: NaN

console.log("\n---ParseInt() Example---");

console.log(parseInt("123 test")); // Output: 123
console.log(parseInt("test 123")); // Output: NaN
console.log(parseInt("  -10.5" + 22)); // Returns -10
console.log(parseInt("0xAF", 16)); // Returns 175 (hexadecimal to decimal)
// (hexNumber, 16) 16 is the Radix or Base-16

console.log("\n---Boolean() Example---");

const toBoolean = Boolean("test");
console.log(toBoolean); // Output: true
// Truthy: true, 1, "string", [], {}.
// Falsy: false, 0, null, undefined, NaN, "", 0n (BigInt zero).
// Note: the Double Logical NOT !! Operator achieves the same result.
JavaScript

The Imprecision of Decimals (Floating-Point Arithmetic)

While Type Coercion covers how JavaScript converts types, it’s essential to recognize a major pitfall in how the Number type itself is handled: decimal imprecision. This is a frequent source of bugs in financial or mathematical applications.

  • The Issue: JavaScript, like most programming languages, uses the industry-standard IEEE 754 format for representing numbers. This format is based on binary floating-point arithmetic, which simply cannot perfectly represent all decimal fractions (such as 0.1 or 0.2).
  • The Result: Simple decimal operations often result in minute, yet incorrect, rounding errors:
// This is the famous unexpected output:
console.log(0.1 + 0.2); // Output: 0.30000000000000004
console.log(0.3 - 0.1); // Output: 0.19999999999999998
JavaScript

How to Fix It (The Integer Hack): Since JavaScript can handle integers (whole numbers) perfectly, the solution is to temporarily convert the decimals into integers before performing the math, and then convert them back. This bypasses the intermediate rounding error.

// To correctly add 0.1 + 0.2:
console.log((0.1 * 10 + 0.2 * 10) / 10); // Output: 0.3 (3/10)
// To correctly subtract 0.3 - 0.1:
console.log((0.3 * 10 - 0.1 * 10) / 10); // Output: 0.2 (2/10)
JavaScript

By multiplying by a power of ten (e.g., 10, 100, 1000) sufficient to clear the decimals, you force JavaScript to perform the calculation using safe, reliable integer math.

< Previous
Next Lesson >

  • JavaScript Tutorial
  • JavaScript Introduction
    • JavaScript’s History
    • Getting Started with JavaScript
    • JavaScript’s Syntax & Structure
    • JavaScript Variables
    • JavaScript Data Types
    • JavaScript Escape Sequences
    • JavaScript Operators
    • JavaScript Type Coercion
    • JavaScript Expressions & Statements
  • JavaScript Built-in Objects & Methods
    • JavaScript Primitives & Methods
    • JavaScript String Properties & Methods
    • JavaScript Number Methods & Global Functions
    • JavaScript Math Object
    • JavaScript Date Object
  • JavaScript Control Flow and Collections
    • JavaScript Conditional Logic
    • JavaScript Try/Catch Synchronous Error Handling
    • JavaScript Arrays
    • JavaScript Array Methods
    • JavaScript Loops
    • JavaScript Objects
    • JavaScript Objects vs. JSON
    • JavaScript Primitive vs. Reference Values

The Newbie Template Bundle

The 12 Website Bundle Pack

Subscribe on YouTube

Web Development Courses

The HTML Email Mastery Course - Build Responsive HTML Email Templates.

Latest Tutorial Posts

  • The HTML Email Mastery Course - Build Responsive HTML Email Templates.w3newbie.com
    HTML Email Mastery Course CouponOctober 12, 2020 - 8:10 pm
  • Create A 5 Page Website With PHP Includes, HTML5, CSS3 & Bootstrap 4w3newbie.com
    Create A 5 Page Website With PHP Includes, HTML5, CSS3 & Bootstrap 4April 22, 2019 - 1:48 pm
© w3newbie.com, 2026. Terms of Use. Privacy Policy.
Scroll to top Scroll to top Scroll to top