Which equals operator (== vs ===) should be used in JavaScript comparisons?
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace ==
(two equals signs) with ===
(three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0
inside of an if
statement.
Is there a performance benefit to replacing ==
with ===
?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==
?
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.
Reference: Javascript Tutorial: Comparison Operators
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.
A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning reference types. For reference types ==
and ===
act consistently with one another (except in a special case).
The special case is when you compare a literal with an object that evaluates to the same literal, due to its toString
or valueOf
method. For example, consider the comparison of a string literal with a string object created by the String
constructor.
Here the ==
operator is checking the values of the two objects and returning true
, but the ===
is seeing that they're not the same type and returning false
. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String
constructor to create string objects.
Reference
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
Using the ==
operator (Equality)
Using the ===
operator (Identity)
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.
In the answers here, I didn't read anything about what equal means. Some will say that ===
means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.
So, let's take the following code:
The same here:
Or even:
This behavior is not always obvious. There's more to the story than being equal and being of the same type.
The rule is:
For value types (numbers):a === b
returns true if a
and b
have the same value and are of the same type
For reference types:a === b
returns true if a
and b
reference the exact same object
For strings:a === b
returns true if a
and b
are both strings and contain the exact same characters
Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)
Now it becomes interesting:
But how about this?:
I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a
is of type Object
, while b
is of type string
. Just remember that creating a string object using the String
constructor creates something of type Object
that behaves as a string most of the time.
An interesting pictorial representation of the equality comparison between ==
and ===
.
Source: http://dorey.github.io/JavaScript-Equality-Table/
When using three equals signs for JavaScript equality testing,
everything is as is. Nothing gets converted before being evaluated.
When using two equals signs for JavaScript equality testing, some
funky conversions take place.
Moral of the story: Use three equals unless you fully understand the
conversions that take place for two-equals.
Let me add this counsel:
If in doubt, read the specification!
ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".
Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.
Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
1. If Type(x) is different from Type(y), return false.
2. If Type(x) is Undefined, return true.
3. If Type(x) is Null, return true.
4. If Type(x) is not Number, go to step 11.
5. If x is NaN, return false.
6. If y is NaN, return false.
7. If x is the same number value as y, return true.
8. If x is +0 and y is −0, return true.
9. If x is −0 and y is +0, return true.
10. Return false.
11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.
Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?
Not so fast!
Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.
If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!
Aidiakapi wrote this in a comment below:
From the specification
11.2.2 The new Operator:
If Type(constructor) is not Object, throw a TypeError exception.
With other words, if String wouldn't be of type Object it couldn't be used with the new operator.
new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.
And this finally means: new String("a") !== "a".
In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.
I tested this in Firefox with Firebug using code like this:
and
My results (tested five times each and averaged):
So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===
. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.
In JavaScript it means of the same value and type.
For example,
but
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.
It checks if same sides are equal in type as well as value.
Example:
Common Example:
Javascript execution flow diagram for strict equality / Comparison '==='
Javascript execution flow diagram for non strict equality / comparison '=='
Why ==
is so unpredictable?
What do you get when you compare an empty string ""
with the number zero 0
?
true
Yep, that's right according to ==
an empty string and the number zero are the same time.
And it doesn't end there, here's another one:
Things get really weird with arrays.
Then weirder with strings
It get's worse:
When is equal not equal?
Let me say that again:
And this is just the crazy stuff you get with primitives.
It's a whole new level of crazy when you use ==
with objects.
At this point your probably wondering...
Why does this happen?
Well it's because unlike "triple equals" (===
) which just checks if two values are the same.
==
does a whole bunch of other stuff.
It has special handling for functions, special handling for nulls, undefined, strings, you name it.
It get's pretty wacky.
In fact, if you tried to write a function that does what ==
does it would look something like this:
So what does this mean?
It means ==
is complicated.
Because it's complicated it's hard to know what's going to happen when you use it.
Which means you could end up with bugs.
So the moral of the story is...
Make your life less complicated.
Use ===
instead of ==
.
The End.
JavaScript ===
vs ==
.
It means equality without type coercion
type coercion means JavaScript do not automatically convert any other data types to string data types
In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.
But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('trn' == 0)
is true.
The equal comparison operator == is confusing and should be avoided.
If you HAVE TO live with it, then remember the following 3 things:
EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT
** STRANGE: note that any two values on the first column are not equal in that sense.**
There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.
Yes! It does matter.
===
operator in javascript checks value as well as type where as ==
operator just checks the value (does type conversion if required).
You can easily test it. Paste following code in an HTML file and open it in browser
You will get 'false' in alert. Now modify the onPageLoad()
method to alert(x == 5);
you will get true.
It's a strict check test.
It's a good thing especially if you're checking between 0 and false and null.
For example, if you have:
Then:
All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.
So with the same thing as above, but a strict test:
===
operator checks the values as well as the types of the variables for equality.
==
operator just checks the value of the variables for equality.
JSLint sometimes gives you unrealistic reasons to modify stuff. ===
has exactly the same performance as ==
if the types are already the same.
It is faster only when the types are not the same, in which case it does not try to convert types but directly returns a false.
So, IMHO, JSLint maybe used to write new code, but useless over-optimizing should be avoided at all costs.
Meaning, there is no reason to change ==
to ===
in a check like if (a == 'test')
when you know it for a fact that a can only be a String.
Modifying a lot of code that way wastes developers' and reviewers' time and achieves nothing.
Simply
==
means comparison between operands with type conversion
&
===
means comparison between operands without type conversion
Type conversion in javaScript means javaScript automatically convert any other data types to string data types.
For example:
A simple example is
The top 2 answers both mentioned == means equality and === means identity. Unfortunately, this statement is incorrect.
If both operands of == are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true. Otherwise,
the two are not equal.
In the code above, both == and === get false because a and b are not the same objects.
That's to say: if both operands of == are objects, == behaves same as ===, which also means identity. The essential difference of this two operators is about type conversion. == has conversion before it checks equality, but === does not.
As a rule of thumb, I would generally use ===
instead of ==
(and !==
instead of !=
).
Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).
However there is one single exception:== null
is an efficient way to check for 'is null or undefined':
For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull
relaxing option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.
From the core javascript reference
===
Returns true
if the operands are strictly equal (see above)
with no type conversion.
The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...
Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...
Which obviously during runtime does very undefined things...
Google for implicit conversions in C++ and STL to get some of the arguments against it...
Equality comparison:
Operator ==
Returns true, when both operands are equal. The operands are converted to the same type before being compared.
Equality and type comparison:
Operator ===
Returns true if both operands are equal and of the same type. It's generally
better and safer if you compare this way, because there's no behind-the-scenes type conversions.
*Operators === vs == *
null and undefined are nothingness, that is,
Here a
and b
do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.
So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.
This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?