Friday, 9 September 2016

JavaScript Coercion

Java script is weird. We know that. Here is one of the weird behavior.Let us look into the below two lines of code. In most of the programming languages, it will thrown as error "Can not compare Boolean to number". But java script won't throw an error and executes the code.

1
2
console.log(1<2<3);//true
console.log(3>2>1);//false

Java script will execute the above lines, that is fine. But why the first line is true and second line is false? On a plain sight any one can think of that if first line is true then second also should be true right. It is not. Let us see why this weird behavior. To understand this behavior we need to know the coercion.

What is Coercion?

In Java script coercion is treated as error and unexpected behavior. But it is a feature of Java script and we need to know how to use it. Coercion is will be applicable only on "==" and logical operators operator.

Type Coercion means if the data types operands of an operator are different. One of the operator is type castes to other operators type. Or both operands will be converted to a common data type.


1
console.log(5+"7"); //57

In a above line 5 is converted into string and + is concatenation operator. So output will become 57. This kind of implicit type casting is called coercion.

Line 1 :
Now try to solve the above problem. In the first line there are two operators and precedence will be left to right.


1
2
3
4
5
6
7
Console.log(1<2<3);
//Step 1: 1<2 is true.
//Step 2: result of the  1 < 2 will be placed in console.log.
Console.log(true < 3);
//step 3: Coercion will happen then true will be converted to number. true => 1.
//Step 4: 
Console.log(1<3); // is true.

Line 2:
Now we see the second line of code execution step by step.


1
2
3
4
5
6
7
Console.log(3>2>1);
//Step 1: 3>2 is true.
//Step 2: 
Console.log(true > 1);
//Step 3: Coercion will happen then true will be converted to number. true => 1.
//Step 4: 
Console.log(1 > 1); // is false.

This what happened in above code. Coercion happened. If you are not comfortable with coercion use "===" triple equal. "===" will compare data type and value both.

Please refer the coercion table..



No comments:

Post a Comment