Which equality operator (== vs. ===) should be used in JavaScript comparisons?
P粉023650014
2023-08-23 12:29:52
<p>I'm using JSLint to explore JavaScript and it returns many suggestions to replace <code>==</code> (two equal signs) with <code>===</code> ( three equal signs) when performing operations such as comparing <code>idSele_UNVEHtype.value.length == 0</code> within an <code>if</code> statement. </p>
<p>Is there a performance benefit to replacing <code>==</code> with <code>===</code>? </p>
<p>Any performance improvements would be welcome as there are many comparison operators. </p>
<p>Will there be a performance gain over <code>==</code> without type conversion? </p>
Use the
==operator (Equal )Use
===operator(Identity)This is because the equality operator
==does a type cast , which means the interpreter will implicitly try to convert the value before comparing.On the other hand, the identity operator
===does not do type coercion and therefore does not convert the value when comparing.The strict equality operator (
===) behaves the same as the abstract equality operator (==), except that no type conversion is performed and the types must be the same. considered equal.Reference:JavaScript Tutorial: Comparison Operators
==The operator will compare for equality after any necessary type conversions.===The operator does not perform a conversion, so if the two values are not of the same type,===will simply returnfalse. Both are equally fast.Quoting Douglas Crockford’s wonderful JavaScript: The Good Parts一个>,
renew
@Casebash in the comments and @Phillipe Laybaert's answer about objects. For objects,
==and===behave identically to each other (except in special cases).var a = [1,2,3]; var b = [1,2,3]; var c = { x: 1, y: 2 }; var d = { x: 1, y: 2 }; var e = "text"; var f = "te" + "xt"; a == b // false a === b // false c == d // false c === d // false e == f // true e === f // trueThe special case is when you compare a primitive to an object that evaluates to the same primitive, due to its
toStringorvalueOfmethod. For example, consider comparing a string primitive to a string object created using theStringconstructor."abc" == new String("abc") // true "abc" === new String("abc") // falseHere
==operator checks the value of both objects and returnstrue, but===sees that they are of different types and returnsfalse. Which one is correct? It really depends on what you're comparing. My suggestion is to bypass this problem entirely and just don't use theStringconstructor to create a string object from a string literal.refer to
https://262.ecma-international.org/5.1/#sec-11.9 .3