Java script is an integral part of any web development.
To check the equality between two variables or objects it provides us two different ways.
One way is "==" which is known as "equality operator" which perform "type coercion"
, and other way is using "===" known as "identity operator".
-
Let's try to understand their behavior.
- If we're comparing two operands with same data types then both of them will behaves as per our expectation.
e.g.
1 == 1 (true) 1===1 (true) "one" == "one" (true) "one" === "one" (true) 3.1 == 3.1 (true) 3.1 === 3.1 (true) false == false (true) false === false (true) 1 == 2 (false) 1 === (false)
- Problem comes when we perform equality against two different data source. Means both of the operands are of different data-types.
In this scenario equality operator first perform the type coercion, means value of both of them will 1st get converted to same data type.
So it is preferable to use the parseInt(), & parseFloat() method if we're comparing any string value of number data-type ("1", "3"). Another problem & more confusing point is that type conversing using parseInt() is different from the type conversion used by "type coercion" e.g. empty string "" will get converted to number 0 using type coercion but it will return not a number NaN if we're suing parseInt("")e.g. 1st "1" == 1, here string "1" will first get converted to number one (1) then comparison will be done resulting into "true". e.g. 2nd "" == 0, here empty string "" will first get converted to number zero (0) then comparison will be done resulting into "true".
equality operator "=="
Result
identity operator "==="
Result
null == undefined true null === undefined false Infinity == "Infinity" true Infinity === "Infinity" false NaN == NaN false NaN === NaN false NaN == "NaN" false NaN === "NaN" false false == "0" true false === "0" false "" == 0 true "" === 0 false false == 0 true false === 0 false false == "false" false false === "false" false true == 1 true true === 1 false true == "1" true true === "1" false true == "true" false true === "true" false
Comments
Post a Comment