Back to all posts

Type Casting and Type Conversion in JavaScript


Type conversion (or typecasting) means the transfer of data from one data type to another.

Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data type.

Explicit conversion is a process of converting a value from one type to another by explicitly calling a conversion function or using a specific syntax.

Example:

Let’s say we have a string variable “numString” that contains a numeric string value:

let numString = "42";

To convert this string into a number, we can use the Number() function:

let num = Number(numString);
console.log(num); // Output: 42

Type Conversion/Coercion:

Type conversion (also known as type coercion) refers to the process of implicitly converting values from one type to another in JavaScript.

JavaScript automatically performs type conversions when you perform operations between different types of values.

Example:

Let’s consider an example where we have a number and a string, and we concatenate them using the + operator:

let number = 42;
let string = "Hello";

let result = number + string;
console.log(result); // Output: "42Hello"
console.log(typeof result); // Output: String

In this example, JavaScript implicitly converts the number 42 to a string and performs string concatenation.

Explicit Type Casting

Explicit type casting is the process of converting a value from one type to another by explicitly calling a conversion function or using a specific syntax.

Example: Let’s assume we have a number and we want to convert it to a string using the toString() method:

let number = 42;
let str = number.toString();
console.log(str); // Output: "42"

In this example, we explicitly call the toString() method on the number variable to convert it to a string.

Implicit Type Casting:

Implicit type casting, also known as implicit type conversion, occurs when JavaScript automatically converts values from one type to another without any explicit instruction.

Example: Consider the following example where we add a number and a boolean:

let number = 42;
let bool = true;

let result = number + bool;
console.log(result); // Output: 43

In this example, JavaScript implicitly converts the boolean value true to a number (1) before performing the addition operation.

Remember to use type casting and conversion operations judiciously, ensuring that they align with your intended logic and avoid potential pitfalls or unintended consequences in your code.