JavaScript:JavaScript Type Conversion and Coercion with Examples
JavaScript•Type Conversion

JavaScript Type Conversion and Coercion with Examples

Understand how JavaScript converts types automatically (coercion) and how to convert explicitly to prevent bugs.

Syntax

const num = Number("123"); const str = String(456); const bool = Boolean(val);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
Number()Constructor FunctionParses string/boolean into numeric value or NaN.
Boolean()Constructor FunctionConverts truthy/falsy values into true/false.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Explicit Type Conversion
const rawInput = "42.8";
const numericVal = parseFloat(rawInput);
const integerVal = parseInt(rawInput, 10);

console.log("Float:  ", numericVal, typeof numericVal);
console.log("Integer:", integerVal, typeof integerVal);

// Falsy values check in JavaScript
const falsyChecks = [Boolean(0), Boolean(""), Boolean(null), Boolean(undefined), Boolean(NaN)];
console.log("All Falsy:", falsyChecks.every(v => v === false));

// Truthy values
console.log("Empty array truthy:", Boolean([]));
console.log("Empty object truthy:", Boolean({}));
Expected Output:
Float:   42.8 number
Integer: 42 number
All Falsy: true
Empty array truthy: true
Empty object truthy: true

How It Works: Step-by-Step

  • Lines 2-4: Parses numeric strings with explicit base 10 parseInt and parseFloat.
  • Lines 10-11: Verifies the 5 primary falsy values in JavaScript.
  • Lines 14-15: Shows that empty arrays and objects evaluate to truthy.

Key Concepts

  • Always pass radix 10 to parseInt(str, 10) to avoid legacy octal parsing.
  • The 7 falsy values in JS: false, 0, -0, 0n, "", null, undefined, and NaN.
  • Empty arrays [] and objects {} are truthy in JavaScript.

Common Mistake: Comparing NaN with === operator

In JavaScript, NaN is never equal to anything, including itself. Use Number.isNaN().

❌ Incorrect
if (val === NaN) { /* Never true! */ }
✅ Correct
if (Number.isNaN(val)) { /* Correctly detects NaN */ }

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler