javascript tutorial - [Solved-5 Solutions] Operator (== vs ===) - javascript - java script - javascript array
Problem:
Which equals operator (== vs ===) should be used in JavaScript comparisons ?
Solution 1:
- The identity
(===)
operator behaves identically to the equality(==)
operator except no type conversion is done, and the types must be the same to be considered equal. - The
==
operator will compare for equality after doing any necessary type conversions. The==
operator will not do the conversion, so if two values are not the same type===
will simply return false. Both are equally quick. - To quote Douglas Crockford's excellent JavaScript: The Good Parts,
- JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.
Solution 2:
Using the == operator (Equality)
- This is because the equality operator == does type coercion>, meaning that the interpreter implicitly tries to convert the values before comparing.
- On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.
Solution 3:
In JavaScript it means of the same value and type.
For example,
Solution 4:
- The === operator is called a strict comparison operator, it does differ from the == operator.
- Lets take 2 vars a and b.
- For "a == b" to evaluate to true a and b need to be the same value.
- In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.
- Take the following example
- In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.
- In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.
Solution 5:
It checks if same sides are equal in type as well as value.
Example: