Type coercion - an Explanation
Type coercion is undoubtedly one of the more strange parts of JS. Sometimes, it makes a lot of sense.
const count = 1;
const x = " example of type coercion";
console.log(count + x);
// "1 example of type coercion"
In this case, the code tries to add a number and a string together. Since it can't do that, it turns the number 1 into the string "1". Then the two can be added together pretty easily.
You can think of what the JS engine does behind the scenes to coerce the types like this.
const count = 1;
const x = " example of type coercion";
console.log(count.toString() + x);
// "1 example of type coercion"
Type coercion isn't evil. It's a useful tool in many cases. If you want to check to see if a value is defined, you can use type coercion.
const myName = "Joshua Anderson";
if (myName){
console.log("My name is truthy");
console.log("It coerces to true!");
}
What happens here? First, myName is defined as a string. Then, the code hits an if statement. It looks at the value in the if statement, which isn't true or false. Then, the value of myName gets coerced into a boolean.
Since the only non-truthy values in myName are false
, 0
, -0
, 0n
, ""
, null
, undefined
, and NaN
, this value is coerced to true, meaning that the code block runs! That's pretty handy.
But type coercion can also be the cause of some very hard to debug issues.
const accidentalString = "1";
const myNumber = 2;
console.log(accidentalString + myNumber);
// 12
If somehow, a value in your code that should be a number becomes a string, and it is added together with a number, type coercion can make your life a lot more difficult, because it can behave unpredictably.
Typescript is a lifesaver because of this. Although there is a bit of a learning curve, I've found that it is much better to have errors be thrown in development than in production.
Even in vanilla JS, there are some ways that you can try to safeguard your code. The most prominent would be the === operator.
const myNum = 12;
console.log(myNum == "12"); //true
console.log(myNum === "12"); // false
Using the === operator allows you to opt out of type coercion when JS compares two values. This can help your code behave more predictably.