What exactly is type coercion in Javascript?
For example, on the use of ==
instead of ===
?
Type coercion means that when the operands of an operator are different types, one of them will be converted to an "equivalent" value of the other operand's type. For instance, if you do:
boolean == integer
the boolean operand will be converted to an integer: false
becomes 0
, true
becomes 1. Then the two values are compared.
However, if you use the non-converting comparison operator ===
, no such conversion occurs. When the operands are of different types, this operator returns false
, and only compares the values when they're of the same type.
var str = 'dude';
console.log(typeof str); // "string"
console.log(!str); // false
console.log(typeof !str); // "boolean"
Example of a variable which is initially declared as a string being coerced into boolean value with the ! operator
a == b
means javascript will evaluate a
against b
based on if the values can be evaluated equally. For example, false == 0
will evaluate true because 0 is also the value of Boolean false. However, false === 0
will evaluate false because strictly comparing, 0 is not the same physical value as false. Another example is false == ''
So basically loose comparison vs. strict comparison, because javascript is a loosely typed language. That is to say, javascript will attempt to convert the variable based on the context of the code, and this has the effect of making things equal if they are not strictly compared. php also has this behavior.
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.
let me explain type coercion with the following example
Type Coercion means Javascript automatically (on-the-fly) converts a variable from one datatype to another
Ex: 123 + "4"
generally raises an error but in Javascript due to type coercion, it results in 1234
a string
if(23 == "23"){
console.log(" this line is inside the loop and is executed ");
}
In the above code, because of type coercion - JavaScript thinks 23
(number) and "23"
(string) are the same thing. this makes the condition true and prints the console.log
In the other case
if(23 === "23"){
console.log(" this line is inside the loop and is NOT executed");
}
In ===
case Javascript doesn't do Type Coercion, and since 23
is a number and "23"
is String and because of ===
these two datatypes are different and that leads to the false in condition. It does not print the console.log
In simple words
In this case =
it is an assignment operator - which assigns values such as var a = 3;
, etc
(below operators are for comparison)
In this case ==
Javascript converts/coerces the datatype to another and then compares it.
In this case ===
Javascript doesn't convert/coerces the datatype
In order to avoid bugs and for debugging purposes ===
is mostly used
Please let me know the accuracy of the above information.
In Python if you try to add, say, strings and integers, you get an error:
>>> "hi" + 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
Yet in JavaScript, you don't. The 10
gets converted to a string:
> "hi" + 10
"hi10"
"Type coercion" is just a fancy misnomer for the above. In actuality, neither language has "types" in the sense of Java or C or other languages with static type systems. How the languages treat interactions between the various non-statically-typed values is a matter of choice and convention.