JavaScript Type Conversion — Complete Guide
Module 5 — Type Conversion
Type conversion is one of the most important concepts in JavaScript. Since JavaScript is a dynamically typed language, variables can change their data type at runtime. JavaScript often converts values automatically, and developers can also perform conversions manually when needed.
Understanding type conversion is essential for building reliable applications, preventing unexpected bugs, and working effectively with user input, APIs, databases, and JSON data.
In this module, you'll learn:
- What type conversion is
- Implicit Conversion (Type Coercion)
- Explicit Conversion
- Number()
- String()
- Boolean()
- parseInt()
- parseFloat()
- toString()
- JSON.parse()
- JSON.stringify()
- Best practices
What is Type Conversion?
Type Conversion is the process of changing a value from one data type to another.
Example:
1let age = "25"; 2 3console.log(typeof age); 4 5age = Number(age); 6 7console.log(typeof age);
Output
1string 2number
Types of Type Conversion
JavaScript supports two kinds of conversions.
1Type Conversion 2 3│ 4 5├── Implicit Conversion 6│ (Automatic) 7 8└── Explicit Conversion 9 (Manual)
Implicit Conversion (Type Coercion)
Implicit conversion occurs automatically when JavaScript converts one data type into another during an operation.
Example 1
1console.log("10" + 5);
Output
1105
The number 5 is automatically converted into a string.
Internally
1"10" + "5"
Example 2
1console.log("10" - 5);
Output
15
JavaScript converts "10" into a number because subtraction only works with numeric values.
Example 3
1console.log(true + 1);
Output
12
Internally
1true → 1
Example 4
1console.log(false + 10);
Output
110
Example 5
1console.log(null + 5);
Output
15
null becomes 0.
Example 6
1console.log(undefined + 5);
Output
1NaN
Common Implicit Conversion Rules
| Expression | Result |
|---|---|
"5" + 2 | "52" |
"5" - 2 | 3 |
true + 1 | 2 |
false + 5 | 5 |
null + 1 | 1 |
undefined + 1 | NaN |
Explicit Conversion
Explicit conversion means the programmer manually converts one data type into another using built-in functions.
Example
1const age = "23"; 2 3const result = Number(age); 4 5console.log(result);
Output
123
Number()
The Number() function converts a value into a number.
Convert String
1console.log(Number("100"));
Output
1100
Convert Boolean
1console.log(Number(true)); 2console.log(Number(false));
Output
11 20
Convert Null
1console.log(Number(null));
Output
10
Convert Undefined
1console.log(Number(undefined));
Output
1NaN
Invalid Conversion
1console.log(Number("JavaScript"));
Output
1NaN
String()
The String() function converts any value into a string.
1console.log(String(100)); 2console.log(String(true)); 3console.log(String(null));
Output
1"100" 2"true" 3"null"
Boolean()
The Boolean() function converts values into either true or false.
Truthy Values
1Boolean(1) 2Boolean(100) 3Boolean("Hello") 4Boolean([]) 5Boolean({})
All return
1true
Falsy Values
1Boolean(0) 2Boolean("") 3Boolean(null) 4Boolean(undefined) 5Boolean(NaN)
All return
1false
Truthy vs Falsy Values
| Value | Boolean Result |
|---|---|
1 | true |
"Hello" | true |
{} | true |
[] | true |
0 | false |
"" | false |
null | false |
undefined | false |
NaN | false |
parseInt()
parseInt() converts a string into an integer.
1console.log(parseInt("100"));
Output
1100
Decimal Example
1console.log(parseInt("99.99"));
Output
199
Invalid Example
1console.log(parseInt("Hello"));
Output
1NaN
Mixed String
1console.log(parseInt("123px"));
Output
1123
parseFloat()
parseFloat() converts a string into a floating-point number.
1console.log(parseFloat("99.99"));
Output
199.99
Mixed Example
1console.log(parseFloat("99.99px"));
Output
199.99
Number() vs parseInt() vs parseFloat()
| Function | "123" | "123.45" | "123px" |
|---|---|---|---|
| Number() | 123 | 123.45 | NaN |
| parseInt() | 123 | 123 | 123 |
| parseFloat() | 123 | 123.45 | 123.45 |
toString()
The toString() method converts a value into a string.
1const age = 25; 2 3console.log(age.toString());
Output
1"25"
Boolean Example
1const status = true; 2 3console.log(status.toString());
Output
1"true"
String() vs toString()
| Feature | String() | toString() |
|---|---|---|
Works with null | ✅ | ❌ |
Works with undefined | ✅ | ❌ |
| Method | Function | Object Method |
Example
1console.log(String(null));
Output
1"null"
1console.log(null.toString());
Output
1TypeError
JSON.stringify()
Converts a JavaScript object into a JSON string.
1const user = { 2 name: "Ankit", 3 age: 23 4}; 5 6const json = JSON.stringify(user); 7 8console.log(json);
Output
1{"name":"Ankit","age":23}
Type
1console.log(typeof json);
Output
1string
JSON.parse()
Converts a JSON string back into a JavaScript object.
1const json = '{"name":"Ankit","age":23}'; 2 3const user = JSON.parse(json); 4 5console.log(user);
Output
1{ 2 name: "Ankit", 3 age: 23 4}
Real-World Example
Saving Data
1const user = { 2 name: "Ankit", 3 age: 23 4}; 5 6localStorage.setItem( 7 "user", 8 JSON.stringify(user) 9);
Reading Data
1const user = JSON.parse( 2 localStorage.getItem("user") 3); 4 5console.log(user.name);
Type Conversion Table
| Value | Number() | String() | Boolean() |
|---|---|---|---|
"100" | 100 | "100" | true |
true | 1 | "true" | true |
false | 0 | "false" | false |
null | 0 | "null" | false |
undefined | NaN | "undefined" | false |
"" | 0 | "" | false |
"Hello" | NaN | "Hello" | true |
Common Mistakes
Mistake 1
1console.log("5" + 2);
Output
152
Expected
17
Solution
1console.log(Number("5") + 2);
Mistake 2
1console.log(Boolean("false"));
Output
1true
Because any non-empty string is truthy.
Mistake 3
1console.log(parseInt("12.9"));
Output
112
Use parseFloat() if you want decimal values.
Best Practices
- Prefer explicit conversion over relying on implicit type coercion.
- Use
Number()when converting entire numeric strings. - Use
parseInt()for integer parsing andparseFloat()for decimal parsing. - Use
String()when converting values that may benullorundefined. - Use
JSON.stringify()before storing objects inlocalStorageor sending them to APIs. - Use
JSON.parse()to convert JSON strings back into JavaScript objects. - Validate conversions with
Number.isNaN()when working with user input.
Mini Project: User Registration Data Converter
index.html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Type Conversion Demo</title> 6</head> 7<body> 8 9<h2>User Information</h2> 10 11<div id="output"></div> 12 13<script src="script.js"></script> 14 15</body> 16</html>
script.js
1const apiResponse = `{ 2 "name":"Ankit", 3 "age":"23", 4 "salary":"55000.75", 5 "isStudent":"false" 6}`; 7 8const user = JSON.parse(apiResponse); 9 10user.age = Number(user.age); 11user.salary = parseFloat(user.salary); 12user.isStudent = user.isStudent === "true"; 13 14const output = document.getElementById("output"); 15 16output.innerHTML = ` 17 <p><strong>Name:</strong> ${user.name}</p> 18 <p><strong>Age:</strong> ${user.age}</p> 19 <p><strong>Salary:</strong> ${user.salary}</p> 20 <p><strong>Student:</strong> ${user.isStudent}</p> 21`;
Summary
In this module, you learned:
- What type conversion is and why it is important in JavaScript.
- The difference between implicit conversion (type coercion) and explicit conversion.
- How to convert values using
Number(),String(), andBoolean(). - When to use
parseInt()andparseFloat()for parsing numeric strings. - The difference between
String()andtoString(). - How
JSON.stringify()converts JavaScript objects into JSON strings. - How
JSON.parse()converts JSON strings back into JavaScript objects. - Common type conversion pitfalls and best practices for writing predictable, maintainable code.
In the next module, you'll learn JavaScript Control Flow, including if, else, switch, loops (for, while, do...while), break, continue, and for...of/for...in, which are essential for controlling program execution.