JavaScript Fundamentals / JavaScript Basics

Type Conversion

↔️ Type Conversion

JavaScript can automatically convert data from one type to another when required (implicit type conversion), or you can manually convert the data yourself when needed (explicit type conversion).


❓ What is Type Conversion?

Type conversion means changing one data type into another, for example:

  • Number → String

  • Boolean → Number

  • String → Number

  • etc.

JavaScript has two types of conversions:


✈️ Types of Conversion

1. Implicit Type Conversion (Type Coercion)

JS automatically converts the type behind the scenes.

✔️ Examples:

➤ String + Number

"5" + 2   // "52" (Number → String)

➤ Number + Boolean

2 + true  // 3  (true → 1)

➤ Subtraction / Multiplication / Division

"5" - 1   // 4  ("5" → Number)
"5" * 2   // 10
"5" / 2   // 2.5

➤ Comparisons convert types

"5" == 5  // true  (string → number)

2. Explicit Type Conversion

You convert manually using built-in functions.

➤ Convert to Number

Syntax

Example

Result

Number()

Number("20")

20

parseInt()

parseInt("20px")

20

parseFloat()

parseFloat("3.14")

3.14

➤ Invalid conversion gives:

Number("abc") // NaN

➤ Convert to String

Method

Example

String()

String(100) → "100"

.toString()

(100).toString() → "100"


➤ Convert to Boolean

Falsy values become false, everything else → true.

Falsy Values: 0 "" (empty string) null undefined NaN false

Example:

Boolean(0)       // false
Boolean("Hi")    // true
Boolean([])      // true
Boolean({})      // true