This question already has answers here: Which equals operator (== vs ===) should be used in JavaScript comparisons? (48 answers) Closed 2 years ago.
What is the difference between ==
and ===
in JavaScript? I have also seen !=
and !==
operators. Are there more such operators?
==
is ===
with type converting (aka coercion). To really understand what I mean you can look at this JavaScript function that behaves exactly like ==
: stackoverflow.com/a/38856418/984780
==
), also known as the if-same-type-then-strict-equality-comparison-otherwise-treat-null-and-undefined-and-document-dot-all-as-equal-but-if-string-involved-with-number-or-bigint-then-coerce-string-to-respective-numeric-type-but-if-boolean-involved-then-coerce-it-to-number-but-if-object-involved-then-coerce-it-to-primitive-and-if-numeric-types-involved-then-compare-their-numeric-values-with-distinct-infinities-and-nans-being-unequal-and-then-repeat-as-needed operator.
Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0 == false // true
0 === false // false, because they are of a different type
1 == "1" // true, automatic type conversion for value only
1 === "1" // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
===
and !==
are strict comparison operators:
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and: Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another. Two Boolean operands are strictly equal if both are true or both are false. Two objects are strictly equal if they refer to the same Object. Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]
if (input == null) ...
, will it also make the condition true when input is undefined?
new String()===new String()
returns false (different object references). But new String
should be avoided anyway.
Success story sharing
new String()
is not of a string type, it's of an object type, so the === rule for objects applies. Usage of primitive strings, however, often results in coercing the strings intoString
objects, so the difference is subtle. If you were to assignnew String()
to two different objects,s1
ands2
, thevalueOf()
method on each would return a string primitive for each, ands1.valueOf() === s2.valueOf()
would returntrue
.