What exactly is type coercion in Javascript?
For example, on the use of ==
instead of ===
?
Type coercion in javascript occurs when the Javascript engine has to perform a certain operation for which it needs data to be in a certain type. When the engine encounters data in a certain type that is not applicable for the operation it then coerces the data into a certain type. This is needed because variables in javascript are dynamically typed, which means that a given variable can be assigned a value of any type.
if(1){
// 1 gets coerced to true
}
if(4 > '3') {
// 3 gets coerced into a number
}
44 == "44" // true, the string 44 gets converted to a nr
In javascript coercion, all values are converted to true
except for the following values which are coerced to false
:
console.log(!!""); // false
console.log(!!0); // false
console.log(!!null); // false
console.log(!!undefined); // false
console.log(!!NaN); // false
console.log(!!false); // false
Also notice that in the above example that the double ! operator is used. The ! mark operator coerces a value into a boolean with the opposite value. We can use this operator twice to convert any value into a boolean.