Type Conversion
Learn how to convert a value from one data type to another in JavaScript.
What is Type Conversion?
Type conversion means changing a value from one data type to another data type.
For example, a text value such as "100" can be converted into the number 100.
JavaScript type conversion and automatic coercion.
Explicit Type Conversion
In explicit conversion, the developer manually converts a value by using functions such as Number(), String(), or Boolean().
Number()
Converts a value into a number when the value can be converted.
String()
Converts a value into a string.
Boolean()
Converts a value into true or false.
Simple Conversion Flow
String()
Boolean()
Example 1: String to Number
Sometimes numbers come from forms or other sources as text. We can use Number() to convert that text into a number.
const marksText = "85";
const marks = Number(marksText);
console.log("Marks:", marks);
console.log("Type:", typeof marks);
Output
Type: number
Example 2: Number to String
We can use String() when we want to convert a number into text.
const score = 95;
const scoreText = String(score);
console.log("Score:", scoreText);
console.log("Type:", typeof scoreText);
Output
Type: string
Example 3: Value to Boolean
The Boolean() function converts a value into either true or false.
const courseName = "JavaScript";
const emptyValue = "";
console.log("Course Value:", courseName);
console.log("Boolean Value:", Boolean(courseName));
console.log("Empty Value:", emptyValue);
console.log("Boolean Value:", Boolean(emptyValue));
Output
Boolean Value: true
Empty Value:
Boolean Value: false
Automatic Type Conversion
JavaScript can also automatically convert values during some operations. This behavior is called type coercion.
Simple Example
In "5" + 2, JavaScript treats the operation as string concatenation and the result is "52".
Important Point
When you want a predictable result, explicit conversion using Number(), String(), or Boolean() makes your intention clear.
Summary
Type conversion changes a value from one data type to another. JavaScript provides functions such as Number(), String(), and Boolean() for explicit conversion. JavaScript can also perform automatic type coercion during some operations.