How you Should be Using Type Coercion in JavaScript

Daniel Noordegraaf
2 min readJan 15, 2023

--

Coffee cup on desk with computer and sign that says ‘no bad days’
Photo by Ryland Dean on Unsplash

“Why did the programmer force his variables to change types? Because he wanted to show them who’s boss!”

Type coercion in JavaScript refers to the process of converting a value from one data type to another. This can happen automatically in certain situations, such as when using the + operator to add a number and a string together. It can also be done explicitly using methods such as Number(), String(), and Boolean().

Here are a handful of type coercion examples that you might see out in the wild:

Coercion changing a number to a string:

let num = 5;
let str = "5";
console.log(num + str); // "55"

Here, the + operator is used to add a number and a string together. Since the + operator is not just for arithmetic but also for concatenation, JavaScript automatically converts the number to a string so it can be concatenated with the other string.

Converting a string to a number so we can get mathy:

let num = 5;
let str = "5";
console.log(Number(str) + num); // 10

We use the Number() method to explicitly convert the string “5” to a number. This allows us to perform arithmetic with it and the variable num.

Boolean conversion:

let num = 0;
let str = "false";
console.log(Boolean(num) && str); // false

In this example, we use the Boolean() method to explicitly convert the number 0 to a boolean value. We then use the logical operator && to check if the boolean value is true and the string “false” . Since the first operand is false, the whole expression evaluates to false.

More on coerced booleans:

let str = "";
console.log(!str); // true

We can use the “!” operator to negate the value of the variable str. An empty string is also considered a falsy value in JavaScript, so negating it with the “!” operator will convert it to true.

The “!” operator will only coerce the value to a boolean, it will not change the type of the variable. It’s also worth noting that not all values will be coerced to true or false, for instance, when using an object as an operand it will always be coerced to true.

Type coercion can sometimes lead to unexpected results, so it’s best to use it deliberately and with caution. Understanding the rules of type coercion and testing your code thoroughly can help you avoid any issues.

--

--