DEV Community

Cover image for Understanding the Type coercion and Type conversion
James Ayomide
James Ayomide

Posted on

Understanding the Type coercion and Type conversion

Talking about one of the uniqueness of Javascript, the type coercion and conversion is an attribute of that qualification. Let's go on and see why that is>>>.

NB: This is not to show that it doesn't apply in other programming languages.

Type Conversion
Type conversion in JS refers to the programmer manually transforming a value from one data type to another. One of the popular ways by which conversion is done is by using Number() and String() explicit conversion:

let numStr = "78";
let toNumber = Number(numStr) // Converts the string "78" to a number
Enter fullscreen mode Exit fullscreen mode

but beyond that, Do you know it also applies to the use of operators? Let's move further.

Type Coercion
Type Coercion is a process automatically executed by JavaScript when operations involve different data types. JavaScript undertakes the responsibility of transforming one or more operands to a common type to enable the operation.

let numStr = "78";
let toNumber = numStr + 20; // Converts to a number?
// result: 7820
Enter fullscreen mode Exit fullscreen mode

This is where JavaScript is given control over the result of the expression, you would see that the result of toNumber is 7820, this happens because of the "+" operator. Whenever the **"+" **operator is used to add a string to a number it automatically turns the result to a string. But what happens when we use another operator?

let numStr = "78";
let toNumber = numStr - 20; // Converts to a number? YES
// result: 58
Enter fullscreen mode Exit fullscreen mode

It gave us the result we expected when we used the " - " operator. This tells us now that Javascript uses these operators to automatically converts one data type to another.

Why are they both important?
They are important in many scenarios, For instance: Type conversion is important when handling user inputs, if a user enters their age as a string, it needs to be explicitly converted to a number before any calculations.

let ageStr = document.querySelector('.message').value; // 28
let age = Number(ageStr) + 10 // Using type conversion
Enter fullscreen mode Exit fullscreen mode

In Type coercion, this can occur when performing arithmetic operations involving mixed data types. For instance, when displaying a message that combines strings and numbers.

let items = 83;
let message = "Sold, " + items " in total today."; // becomes a string
Enter fullscreen mode Exit fullscreen mode

In Conclusion, Both are important no one is better than the other. Thank you for reading, I'd love to write to you again.💙

Oldest comments (0)