Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

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 coercion diagram

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.

Number("100")
String()

Converts a value into a string.

String(100)
Boolean()

Converts a value into true or false.

Boolean(1)

Simple Conversion Flow

Value → Conversion Function → New Type
Original Value
→
Number()
String()
Boolean()
→
Converted Value

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

Marks: 85
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

Score: 95
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

Course Value: JavaScript
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.