JavaScript Type Conversion
Learn how JavaScript converts values between different data types. Understand implicit and explicit conversion with practical examples and interview questions.
Reading Time
14 min
Lesson
Lesson 6 of 48
What is Type Conversion?
Type conversion is the process of converting a value from one data type to another. JavaScript automatically converts values in some situations (implicit conversion), and developers can also convert values manually (explicit conversion).
Why is Type Conversion Important?
JavaScript is a loosely typed language. Variables can hold values of different data types, so understanding how conversions work helps avoid unexpected bugs.
Types of Conversion
- Implicit (Automatic) Conversion
- Explicit (Manual) Conversion
Implicit Type Conversion
JavaScript automatically converts one data type into another during operations when necessary.
Implicit Conversion Example
Console Output
Click “Run” to see the console output here.
Explicit Type Conversion
Explicit conversion is performed manually using built-in JavaScript functions such as Number(), String(), and Boolean().
Convert to Number
Console Output
Click “Run” to see the console output here.
Convert to String
Console Output
Click “Run” to see the console output here.
Convert to Boolean
Console Output
Click “Run” to see the console output here.
Common Type Conversions
| Expression | Result |
|---|---|
| Number("10") | 10 |
| Number("abc") | NaN |
| String(100) | "100" |
| Boolean(1) | true |
| Boolean(0) | false |
| Boolean("") | false |
| Boolean("Hi") | true |
Truthy and Falsy Values
In JavaScript, every value is either truthy or falsy when evaluated in a boolean context.
Falsy Values
- false
- 0
- -0
- 0n
- "" (empty string)
- null
- undefined
- NaN
Truthy Values
- "Hello"
- []
- {}
- 1
- -1
- Infinity
Common Mistake
Using == performs type conversion before comparison, while === compares both value and type. Prefer === in modern JavaScript.
== vs ===
Console Output
Click “Run” to see the console output here.
Best Practice
Always perform explicit type conversion whenever possible. Avoid relying on JavaScript’s automatic coercion because it can produce unexpected results.
Summary
JavaScript supports both implicit and explicit type conversion. Understanding type coercion helps write predictable and bug-free code.