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:
| Parameter | Type | Description |
|---|---|---|
| Number() | Constructor Function | Parses string/boolean into numeric value or NaN. |
| Boolean() | Constructor Function | Converts truthy/falsy values into true/false. |
Ready-to-Run Code Example
Executable in CompilraRun 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
JavaScript Variables: let, const, and var Explained
Learn how to declare variables in modern JavaScript using let, const, and var with block scoping.
JavaScript Operators: Arithmetic, Comparison & Strict Equality
Explore arithmetic, comparison, logical, and nullish coalescing (??) operators in JavaScript.
JavaScript If...Else, Ternary Operator, and Branching
Control code execution based on conditions using if, else if, else, and ternary expressions.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.