← Back to Chapters

JavaScript Type Conversion

? JavaScript Type Conversion

? Quick Overview

JavaScript can change a value from one data type to another. When JavaScript does this on its own, it is called type coercion. When you do it explicitly in your code, it is called type conversion. Understanding both helps avoid bugs and weird console output.

? Key Concepts

  • Type conversion: Explicitly converting values (e.g., Number("10")).
  • Type coercion: JavaScript automatically converts types during operations.
  • Common targets: Convert values to string, number, or boolean.
  • Helper functions: String(), Number(), Boolean(), parseInt(), parseFloat().
  • Truthy/falsy: Some values become true or false when converted to boolean.

? Syntax and Methods

In practice, you will mostly convert values to strings, numbers, or booleans using built-in functions and constructors. Below are some common patterns.

? Convert to String

You can convert numbers, booleans, or objects to strings using String() or .toString().

? View String Conversion Example
let num = 100;
let str1 = String(num);       // "100"
let str2 = (20).toString();   // "20"

let bool = true;
let str3 = String(bool);      // "true"

console.log(str1, str2, str3);

? Convert to Number

You can convert strings and booleans to numbers using Number(), parseInt(), or parseFloat().

? View Number Conversion Example
let a = "123";
let b = Number(a);            // 123

let c = parseInt("45px");     // 45
let d = parseFloat("12.34");  // 12.34

let e = Number(true);         // 1
let f = Number(false);        // 0

console.log(b, c, d, e, f);

✅ Convert to Boolean

Use Boolean() to convert a value to a boolean. Falsy values like 0, "", null, undefined, and NaN become false. Everything else is generally truthy.

? View Boolean Conversion Example
console.log(Boolean(0));        // false
console.log(Boolean(""));       // false
console.log(Boolean("hello"));  // true
console.log(Boolean(123));      // true

? Automatic Type Coercion

JavaScript sometimes converts types automatically, especially with operators like + and -:

? View Type Coercion Example
console.log("5" + 1);      // "51"  (1 is converted to string)
console.log("5" - 1);      // 4     ("5" is converted to number)
console.log(true + 1);     // 2     (true becomes 1)
console.log(false + "1");  // "false1"

⚖️ parseInt vs Number

Number() tries to convert the whole string. parseInt() and parseFloat() read as much numeric content as possible from the start of the string.

  • Number("10.5")10.5
  • parseInt("10.5")10
  • Number("10px")NaN
  • parseInt("10px")10
? View parseInt vs Number Example
console.log(Number("10.5"));    // 10.5
console.log(parseInt("10.5"));  // 10

console.log(Number("10px"));    // NaN
console.log(parseInt("10px"));  // 10

? When to Use Type Conversion

  • Reading user input from forms (strings) and converting to numbers for calculations.
  • Working with API responses where numbers are often returned as strings.
  • Checking if a value is present or empty using boolean conversion.
  • Formatting values as strings before displaying them in the UI.

? Live Output & Explanation

From the examples above:

  • String(100) becomes "100", and String(true) becomes "true".
  • Number("123") gives 123, while Number("10px") gives NaN because of extra text.
  • parseInt("45px") reads the starting number and returns 45.
  • Boolean(0) and Boolean("") are false, but Boolean("hello") is true.
  • "5" + 1 results in a string ("51"), while "5" - 1 results in a number (4).

These behaviours show why understanding type conversion and coercion is important: the same operator can give different results depending on the types of its operands.

? Tips & Best Practices

  • Use Number() for precise conversion; it returns NaN if the whole string is not a valid number.
  • Use parseInt() and parseFloat() when you expect extra characters after the numeric part.
  • Use parseFloat() instead of parseInt() if you need decimal values.
  • Boolean() is useful to quickly check if a value is "truthy" or "falsy".
  • Be careful using + with strings: if either operand is a string, the result will be a string concatenation.
  • When in doubt, convert values explicitly instead of relying on automatic coercion.

? Try It Yourself

  • Convert a boolean value to a string using String() and log it to the console.
  • Use parseInt() and Number() on the same string (like "50px") and compare the results.
  • Experiment with Boolean() on different values such as "0", " " (space), [], and {}.
  • Write a small function that takes a user input string and safely converts it to a number, handling invalid input with a message.