type coercion and === operator in javascript

type coercion and === operator in javascript

Type coercion is where you have variables declared & assigned to a value and you are operating on those variables. There are certain points of time where the interpreter will have to do automatic type conversions to equivalent value of the other operands type for you in order to make operations work. Type coercion is the thing that javascript does automatically for us. Many languages supports this feature.

Suppose you are dealing with 2 variables of different types and you want to do some operation(ex. adding) between them. But, how can variables of different data-types be operated upon, unless there is automatic type conversion where interpreter converts one of the variable’s value to the equivalent value of another variable. Now, when the values of the 2 variables are of same data-types so the operation can be done.

123 + "anoop";

What do you think, what should happen. Result is “1234”, a string. Interpreter looks at the 2 operands and found that these are of different data-types, so it converts the number 123 to string “123” and let the operation happen. These kinds of situation happen where operations don’t work unless you do type conversions on the variables taking part in operation. Now its upto the interpreter(which follows the specs) for choosing the operand on whom type coercion is to be performed, javascript has its own coercing rules.

== operator compares the 2 values and returns true/false. Javascript does type coercion on == operands. Let’s take an example.

var a = 20;
var b = "20";
if(a == b){
console.log("equal");
}

Javascript sees both the operands are of different types, so it one of the operands to the compatible type. To see which operand is converted you can use typeof operator inside if block.

Javascript designers wanted the language to be very easy to use. In order to achieve this they introduced type coercion on == operator, to help developers. Remember, javascript is very forgiving, it makes assumptions as to what you are trying to achieve even if you are doing any mistake. But due to this developers find it very frustrating as it started breaking their codes. Now to resolve this issue javascript designers went ahead and rolled out === operator which does the same thing as == operator do except type coercion. So, its called strict equals operator. And, it is the right way of performing equality operation in javascript. Or, in another words === operator compares both, the data-type and the value.

Additionally, let me also educate you about this. In Javascript values of all types has a corresponding boolean value associated to it.

var a = undefined; //false
var b = null; //false
var c = 0; // false
var d = 1; //true. All non-zero values represent true
var e = ""; //false
var f = "anoop"; //true. All non-empty strings represent true.

Leave a Reply

Your email address will not be published. Required fields are marked *