JavaScript Type Conversion

Type conversion, also known as type coercion, is the process of converting a value from one data type to another in JavaScript.

It occurs implicitly or explicitly and is essential for performing various operations and comparisons.

Let's explore the different aspects of type conversion with code examples:

Implicit Type Conversion

Implicit type conversion happens automatically when values of different data types are used together in an operation.


const num = 5 
const str = "Number: " + num 

console.log(str); // Output: "Number: 5"

In the above example, the number 5is implicitly converted to a string and concatenated with the string "Number: ".

Example


const num = 5 
const str = "Number: " + num 

console.log(str); // Output: "Number: 5"

Explicit Type Conversion

Explicit type conversion, also known as type casting, is performed using built-in functions or constructors to convert values from one type to another.


const str = "123"; 
const num = Number(str)

console.log(num); // Output: 123

Here, the string "123"is explicitly converted to a number using the Number()constructor.

Example


const str = "123"; 
const num = Number(str)

console.log(num); // Output: 123

String Conversion

Values can be converted to strings using the String()function or the toString()


let str = "123"; 
let num1 = Number(str)
let num2 = ++num1

console.log(num1); // Output: 123
console.log(num2); // Output: 124

Both, String(str)and +strconvert the string "123"to the number 123.

Example


let str = "123"; 
let num1 = Number(str)
let num2 = ++num1

console.log(num1); // Output: 123
console.log(num2); // Output: 124

Boolean Conversion

Values can be converted to booleans using the Boolean()function or the double negation (!!) operator.


const str = "Hello"
const bool1 = Boolean(str)
const bool2 = !!str

console.log(bool1); // Output: true
console.log(bool2); // Output: true

Both, Boolean(str)and !!strconvert the non-empty string "Hello"to true

Example


const str = "Hello"
const bool1 = Boolean(str)
const bool2 = !!str

console.log(bool1); // Output: true
console.log(bool2); // Output: true

Type conversion is an essential concept in JavaScript that allows for flexible manipulation and comparison of data.