Which equals operator (== vs ===) should be used in JavaScript comparisons?

5 673

1 744

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 ==?

bcasp

Posted 2008-12-11T14:19:49.123

Reputation: 28 770

257

Just in case anyone was wondering in 2012: === is way faster than ==. http://jsperf.com/comparison-of-comparisons

– Ry- – 2012-07-03T23:02:38.803

25@minitech it should be as it does not do type conversion – Umur Kontacı – 2012-07-14T19:10:25.203

19@minitech, I doubt anyone is going to make their application noticeably faster by using === over ==. In fact, the benchmark doesn't show a big difference between both on modern browsers. Personally, I usually use == everywhere unless I really need strict equality. – this.lau_ – 2012-12-25T09:09:27.020

2@Laurent: There were a lot of mentions of == being faster than === before. I agree, the speed doesn’t make a difference. I personally use === everywhere unless I really need loose equality :) – Ry- – 2012-12-25T15:17:06.813

4@minitech: Even in your jsPerf, the results vary by browser. According to the ECMAScript spec, there is no reason why either operator should be faster for those comparisons anyway since they run the same steps. – Tim Down – 2013-02-28T17:37:17.170

1

@TimDown: I realize that; it was in response to some other answer/comment/article/something that claimed that == was faster than ===. (http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use#comment19382344_359494)

– Ry- – 2013-02-28T17:41:51.030

2Here's a chart of how some "falsy" values compare. – Nosredna – 2009-06-05T19:21:14.247

5

Here is the part of Crockford's JS The Good Parts talk where he discusses the === and == operators: http://www.youtube.com/watch?feature=player_detailpage&v=hQVTIJBZook#t=922s If it doesn't play, it's at 15:20

– davidhiggins – 2013-04-22T16:17:00.963

Here is a detailed article on comparison of === vs == – Zaheer Ahmed – 2014-01-04T16:56:52.383

if i don't replace (==) with (===) as given in JSLint warning messages.. are there chances that script will break – Chitrank Samaiya – 2014-04-18T12:31:00.637

3@ChitrankSamaiya Yes, code can break, "1" == 1 is true while "1" === 1 is false. If your code is relying on comparing for example strings and numbers in this way it will break. But your code shouldn't rely on these things, which is exactly why people use JSLint. – ivarni – 2014-06-28T11:56:51.770

See also the Javascript Equality Table: http://dorey.github.io/JavaScript-Equality-Table/

– blaze – 2015-01-06T03:18:58.203

3@PaulDraper You're exactly correct. If one notices an opportunity for optimization that clearly doesn't reduce readability nor maintainability nor functionality it is always good practice to issue such optimization. – jbowman – 2015-04-29T20:07:56.060

134

To whom it might be interested in the same subject === vs ==, but in PHP, can read here: http://stackoverflow.com/questions/2401478/why-is-faster-than-in-php/3333581

– Marco Demaio – 2010-12-31T12:33:37.700

@MarcoDemaio In 2018 the tests don't show anything other than noise. I ran the tests 5 times and received very mixed results with each subsequent test. I even stopped other active processes on my computer to add as little pollution as possible and these tests simply do not reflect what you said they did 6 years ago. Tested in Chrome 66. I received results where === was faster when true, where it was slower when true, and where == was faster when true and where == was slower than true. So from what I see now, the tests show no clear difference. – Lev – 2018-05-15T09:21:24.390

== converts, === does not. I have made a video with an example: https://youtu.be/ik5E5n36K4U

– Tomasz Smykowski – 2018-04-23T20:51:55.387

Answers

5 898

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:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true

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.


Update:

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).

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           // true

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.

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

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

Bill the Lizard

Posted 2008-12-11T14:19:49.123

Reputation: 287 653

77"...the rules by which they do that are complicated and unmemorable..." Now such statements make you feel so safe when programming... – Johan – 2011-12-09T16:24:46.440

5@EvanPlaice Nonsense. References to objects (and there are no other references) are values in these languages. In fact, there is no such thing as a reference type where the implementation is concerned; that is purely a specification mechanism. – PointedEars – 2012-05-29T21:25:50.953

1

A good question of the performance differences: http://stackoverflow.com/questions/8044750/javascript-performance-difference-between-double-equals-and-triple-equals

– Eric – 2012-09-30T19:06:32.150

143Sometimes JavaScript's type system makes me want to run away screaming. – Yawar – 2012-11-08T04:06:58.720

4So assuming types are the same - is === actually faster? :) – ibz – 2008-12-26T09:40:47.557

2Still I don't understand why {} === {} returns false. I totally understand these are not the same object in memory, but still this is of the same type and the same value... – Laurent S. – 2013-04-02T15:34:03.547

205=== is not quicker if the types are the same. If types are not the same, === will be quicker because it won't try to do the conversion. – Bill the Lizard – 2008-12-31T03:02:11.710

8@Bartdude They aren't considered to be of the same value because they are not the same object. Objects could be so complicated, that it would be ridiculous to try and compare them for likeness of value. Consider 2 objects with many nested properties, some of which may be functions. How would you go about comparing the value of that? – 1nfiniti – 2013-05-05T15:10:05.663

219Replacing all ==/!= with ===/!== increases the size of the js file, it will take then more time to load. :) – Marco Demaio – 2010-03-31T09:22:07.890

=== type and value are same, == is evil, if they aren't same type,they will convert type before compare .so just use === ,and no need use == – Amitābha – 2013-08-22T15:03:19.180

4@MarcoDemaio pal using !==/=== will save you more space than you think because if you don't use them you will be writing code like if(val != 0 && val != '') instead of if(val !=== 0). – Allan Chua – 2013-10-21T15:14:37.447

10

Should we really never use ==? Have you seen this response

– Casebash – 2010-06-14T04:59:58.040

6@Casebash: Yes, I've seen that. That answer doesn't really compare == and ===, which is what this question is about. For every test I've run using reference types == and === act consistently with one another except for one. That's the case pointed out in the comments where new String("abc") == "abc" returns true, but new String("abc") === "abc" returns false. My advice in light of this is to not use the String constructor, and always use ===. – Bill the Lizard – 2010-06-14T14:37:53.687

1But presumably it's never slower, right? – Ray Hidayat – 2009-02-01T21:14:58.197

468=== will never be slower than ==. They both do type checking, so === doesn't do anything extra compared to ==, but the type check may allow === to exit sooner when types are not the same. – Bill the Lizard – 2009-02-02T04:17:55.787

3@Bill The update is technically the 'right' answer. === is reference equality, == is value equality. – Evan Plaice – 2010-06-25T07:30:52.597

3It could be worth noting that "abc" === String("abc") is true. Oddly enough. – Brian M. Hunt – 2014-02-21T13:41:11.553

1Can you address why [1,2,3] < [1,2,4] //true and [1,2,3] <= [1,2,4] //true? I have never understood this. – lampwins – 2014-04-05T02:45:42.627

32From Crockford: "The lack of transitivity is alarming." If you develop software and don't find lack of transitivity in a comparison operator alarming, or if speed comparison between == and === or file size/load time take precedence in your mind over transitive determinism of a comparison operator's behavior, you may need to go back and start over. – jinglesthula – 2014-05-29T20:31:13.047

1

note the difference between type "coercion" vs type "casting" vs type "convertion", javascript in this case uses type coercion: http://stackoverflow.com/questions/8857763/what-is-the-difference-between-casting-and-coercing

– Adrien Be – 2014-07-23T12:05:09.803

Found this good article from MDN. Should be useful https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Sameness

– Nipuna – 2014-07-26T09:26:24.370

1@LaurentS. I know - you would think that var a = new Object(), b = new Object; a == b would work. But alas no as they have different attributes (even though they have the same values (in this case there are no attributes), but you catch my drift. – dylnmc – 2015-10-16T14:22:35.900

2"always use === and !==." - I like this approach, but what do I do if I want "1" and 1 to be considered equal somewhere in my code, for example after a JSON import? parseInt? – Blauhirn – 2015-12-30T19:08:14.227

6@Blauhirn Yes, the recommended way is to do manual type coercions (either converting 1 to a string, or converting "1" to a number). The parseInt and parseFloat functions work fine, but you can also use +"1" or Number("1") to convert "1" to a number. Note: there is a big difference between Number("1") and new Number("1")! The first does type coercion, the second creates a new Number object. – Pauan – 2016-01-17T23:01:16.407

Here is JavaScript type conversion table(w3schools)

– K._ – 2016-02-11T16:32:30.097

1"For reference types == and === act consistently with one another (except in a special case)." The "special case" isn't a special case. String literals create string primitives, not string objects, so when you're comparing "abc" with new String("abc"), you're doing a cross-type comparison (value type string primative with reference type object). – T.J. Crowder – 2016-02-22T16:57:44.277

5== and != aren't evil. Their existence and functionality is perfectly inline with the overall concept and application of javascript to begin with. There is no guarantee that any browser, user or server will do anything the way you expect it to--especially considering browsers that don't exist yet--which is why javascript is so dynamic. Maybe browser A interprets the input of a textbox as the "best fit" type, but browser B always interprets as a string. Using === causes a compatibility problem between the two browsers. – Devsman – 2016-05-04T14:01:06.027

4The reason new String("xxx") == "xxx" is because of the toString method. Similar things happen with valueOf. new Number(7) == 7, ({ valueOf : function () { return 8; } }) == 8 both eval to true and eval to false if == is changed to === – Thomas Eding – 2011-03-30T05:15:23.790

2new Number() == "0". Also in Firefox: (function(){}) == "function () {\n}" – Thomas Eding – 2011-03-30T05:18:21.120

2@Devsman yes they are evil, but what you are talking about is a function of the browser NOT of javascript. This is no different than Mozilla creating a function that returns a string, and webkit returns an object. In that case ==/!= doesn't work anyway. And there is a guarantee, anyone who creates a new browser now, HAS to accept the javascript currently being used, because if you can't even bring up the basic web pages like facebook, instagram, or someone's bank. No one is going to use the browser (outside of a niche). – Rahly – 2016-06-27T19:59:42.870

To add to the discussion, Kyle Simpson makes a good case for type coercion via ==. Well worth the read or listen if you have time.

– Brandon Boone – 2016-07-29T02:19:40.137

3I just want to add that jquery will convert a string value in an attribute to a number, $('.foo').attr('data-id'), $('.foo').data('id'), $('.foo').prop('data-id') so if you insist on strict equality comparisons you have to be sure you "convert" the number first to an integer before doing the comparison. ALSO the argument that double equals is "EVIL" is evil. – Shanimal – 2016-10-26T22:07:26.940

3I think === (on the long term) is slower because you have to add extra lines of codes to do possible explicit conversions. However, I love === when it comes to financial calculations because you must do strong-typed work and not leave numbers volatile with unknown conversions. – Shadi Namrouti – 2016-11-22T09:55:28.987

1Logic: if a == b and b == c, then a == c. JS: "0" == 0 and 0 == [], but "0" != []. – sp00m – 2017-11-23T15:31:23.457

== does not use logic. try a === b and b === c, then a === c – ThaJay – 2018-02-28T17:07:53.410

1The people who worry about which is faster in such a meaningless and inconsequential thing as this are the same people who have no issue writing crap code in quadratic big O complexity instead of writing good code. Anyone who knows anything about coding knows that worrying about whether === or == takes longer is complete nonsense. – MattE – 2018-04-24T23:34:46.633

2What if for some reason (bad design?) via different API endpoints it would return the same results but as different types? And for some reason you didn't have access to change the API. Could return "2" or 2. You'd need == there :) – camjocotem – 2018-05-01T12:16:44.897

@MarcoDemaio All those evil constructors, non-numerical objects, jQuery and other libraries add a lot more onto the pay load. Also, using the === will likely take less time to process because the JIST compiler doesn't have to output extra type checking garbage there. – Jack Giffin – 2018-05-13T14:27:47.737

@AllanChua if you want to test if(val != 0 && val != '') , just do if(val). – Marco Demaio – 2018-05-21T12:04:19.163

1== doesn't use logic. It uses the heart. – Dushyant Bangal – 2018-06-06T10:27:37.213

might as well stop using + because it does explicit coersion when you do 1+'1' and "...the rules by which they do that are complicated and unmemorable..." – Dushyant Bangal – 2018-06-06T10:55:52.803

From what I understand "abc" == new String("abc") // true because we are comparing the values while "abc" === new String("abc") // false because although the value is the same these are different objects. The "abc" constant is one object and the new String is a different object thus they are !== not the same – AleAssis – 2018-08-17T20:19:21.827

I'm disappointed that it's so hard to find actual advice is this thread, because this is one of the most helpful pieces of advice for new JS developers: Always use ===/!== to reduce the risk of unexpected bugs. The one exception is that you can safely use x == null to check if x is null or undefined (likewise for x != null). – Andy – 2018-09-10T18:20:53.827

@BrianM.Hunt I think you forgot to use new? 'abc' === new String('abc') is false. String('abc') does not construct a wrapper object, it just performs the default conversion to string on its argument, which is why 'abc' === String('abc'). – Andy – 2018-09-10T18:25:08.883

'' == undefined // false – Andrew – 2018-10-15T20:29:46.563

1 025

Using the == operator (Equality)

true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2;  //true, because "2" is converted to 2 and then compared

Using the === operator (Identity)

true === 1; //false
"2" === 2;  //false

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.

Andreas Grech

Posted 2008-12-11T14:19:49.123

Reputation: 62 166

type coercion vs type casting vs type convertion: http://stackoverflow.com/questions/8857763/what-is-the-difference-between-casting-and-coercing – Adrien Be – 2014-07-23T12:02:16.697

22

Since nobody has mentioned the Javascript Equality Table, here it is: http://dorey.github.io/JavaScript-Equality-Table/

– blaze – 2015-01-06T03:17:19.087

5In the first statement, are you sure that 'true' is converted to 1 and not 1 converted to true? – Shadi Namrouti – 2016-11-22T10:05:58.963

9@Software Monkey: not for value types (number, boolean, ...) – Philippe Leybaert – 2009-06-05T20:00:24.213

Where do the terms "equality" and "identity" come from? The standard does not use those terms. It calls == "abstract equality" and it calls === "strict equality". Granted calling == any kind of "equality" is IMHO awful, since it is not transitive, but why quibble? I take more issue with "identity" though; I think that term is pretty misleading, though it "works." But seriously, who coined the term "identity"? I search the standard and could not find it. – Ray Toal – 2018-02-07T08:03:44.487

572

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:

var a = [1,2,3];
var b = [1,2,3];
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

The same here:

var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

Or even:

var a = { };
var b = { };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

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: the special case...

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:

var a = "12" + "3";
var b = "123";

alert(a === b); // returns true, because strings behave like value types

But how about this?:

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

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.

Philippe Leybaert

Posted 2008-12-11T14:19:49.123

Reputation: 129 217

3Thank you for explaining why new String("123") !== "123". They are different types. Simple, yet confusing. – styfle – 2012-08-26T05:51:54.603

19String objects behave as strings as does any other object. new String should never be used, as that doesn't create real strings. A real string and can be made with string literals or calling String as a function without new, for example: String(0); //"0", Real string, not an object – Esailija – 2012-12-04T23:51:33.737

"".isEmptyString() the . creates a new String object from "" and that object is used as the this value inside String.prototype.isEmptyString. – Garrett – 2014-01-13T00:22:44.310

6But in the cases you detailed, the operator "==" behaves exactly the same. – Yaron Levi – 2015-02-06T10:48:04.363

@YaronLevi YES! This is answer was a little misleading at first because it makes you think == behaves differently in the cases shown, when it doesn't. – Justin – 2015-04-23T14:19:09.310

Just wondering, is there any possibility that two objects with different variable names are exactly the same one? – AGamePlayer – 2015-11-01T01:51:46.847

3new Number() == "0". Also in Firefox: (function(){}) == "function () {\n}" – Thomas Eding – 2011-03-30T05:21:36.517

@AwQiruiGuo - Yes. In the first example of this answer: var a = [1,2,3];, var c = a;, both a and c refer to the same object. – Kevin Fegan – 2016-09-26T13:16:18.013

> numbers: returns true if a and b have the same value and are of the same type true except for NaN which never equals itself even if variable set to NaN is compared with itself – Tomas – 2017-04-25T21:48:39.587

6activa: I would clarify, that the strings are so equal only when they are literals. new String("abc") === "abc" is false (according to my research). – Lawrence Dol – 2009-06-05T19:54:58.580

One of the differences between "abc" and new String("abc") is that the new String provides the prototype object and "abc" doesn't. Also the new String("abc") can be garbage collected. The strict equality can be seen as a && short circuit comparison if(typeof a equals type of b && value of a equals b), so if the types are different, it's going to return false and not even proceed with the comparision of values. – Charles Owen – 2017-07-23T03:11:53.977

567

An interesting pictorial representation of the equality comparison between == and ===.

Source: http://dorey.github.io/JavaScript-Equality-Table/


var1 === var2

When using === for JavaScript equality testing, everything is as is. Nothing gets converted before being evaluated.

Equality evaluation of === in JS


var1 == var2

When using == for JavaScript equality testing, some funky conversions take place.

Equality evaluation of == in JS

Moral of the story:

Use === unless you fully understand the conversions that take place with ==.

SNag

Posted 2008-12-11T14:19:49.123

Reputation: 10 519

I would go even further with the moral: always use ===/!=== but understand the conversion for being able to cope with other people's code – mfeineis – 2015-05-08T11:11:03.547

the running implementation of this table is here: http://www.yolpo.com/embed.html?gist=344311f27fd88a9c2be8

– Zo72 – 2015-06-14T20:25:11.417

2@mfeineis you mean === or !== instead of == or != . Don't want to confuse new coders ;) – katalin_2003 – 2016-06-23T14:04:34.883

1from my experience using three equals can cause problems and should be avoided unless fully understood. two equals produces much better results because 99% of the time I really don't want types to be equal. – vsync – 2017-02-12T08:47:06.307

5@vsync: If you really don't want types to be equal, you should use three equals! – SNag – 2017-04-24T05:19:24.697

The one exception: you can safely use x == null to check if x is null or undefined. – Andy – 2018-09-12T15:40:08.377

256

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".

nalply

Posted 2008-12-11T14:19:49.123

Reputation: 9 885

Result of Type(x) is implied to be the same as typeof ? – Dfr – 2012-11-15T18:35:49.843

@nalply I don't exactly understand the anxiety about the behavior with new String('x'), because I've never seen any code in the wild that uses primitive wrapper objects, and I don't think there's much good reason to, especially not these days. Have you ever encountered code that does? – Andy – 2018-09-10T18:28:06.697

@Andy the problem is malicious or just sloppy third-party code, then you can't assume that nobody uses new String(). – nalply – 2018-09-11T09:46:36.603

If it's sloppy, === is how you will find out. If it's malicious, I think new String() is probably the least of your worries. I understand the concern in theory, but again, do you have any real-world examples? To me it's like the old anxiety that someone could set undefined to another value. – Andy – 2018-09-12T15:34:23.740

96

In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.

Shiki

Posted 2008-12-11T14:19:49.123

Reputation: 14 384

4Yes: Two different objects with the same type and value compare false, i.e., this answer is just wrong. Why does it have 50 upvotes? – alexis – 2013-10-18T10:45:37.800

9@David: correct. That's why this answer is inaccurate (or even wrong) – Philippe Leybaert – 2010-05-31T12:25:27.020

6@David var a = {}, b = {}; a == b returns false. – nyuszika7h – 2011-02-26T18:37:49.883

1I realize this is old, but to clarify why this answer is still "correct" is because in the example var a = {}, b = {}; While both a and b is indeed both an object, but they are not the same value, technically speaking. They are different instances. Note that comparing instances behaves differently than comparing primitives. Which probably adds to this confusion. You will see similar comparison behavior if you use instance version of primitive data types. E.g new String('asdf') or new Number(5). Ex: new Number(5) == new Number(5) is false, even though they hold the same value. – Norman Breau – 2017-05-18T18:02:00.737

1We all forget that a reference to an object is actually a Value Type, as it a pointer to a memory slot. The Object comparison is not comparing the "value of the object" but whether both pointers are the same which would mean they reference the same memory slot. That is a very subtle difference in comparing Types, as the "===" operator really needs to say "if type, value, and reference to the object in memory are the same". – Stokely – 2018-09-03T20:05:25.637

92

I tested this in Firefox with Firebug using code like this:

console.time("testEquality");
var n = 0;
while(true) {
    n++;
    if(n==100000) 
        break;
}
console.timeEnd("testEquality");

and

console.time("testTypeEquality");
var n = 0;
while(true) {
    n++;
    if(n===100000) 
        break;
}
console.timeEnd("testTypeEquality");

My results (tested five times each and averaged):

==: 115.2
===: 114.4

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.

Simon Scarfe

Posted 2008-12-11T14:19:49.123

Reputation: 7 135

4Now, how do these compare when there is an actual type coersion for == operator? Remember, that's when there's a performance boost. – Hubert OG – 2013-07-13T21:13:44.077

1

MAJOR difference when tested properly for the aforementioned reasons of quicker to only check type inequality. https://jsfiddle.net/4jhuxkb2/

– Doug Morrow – 2015-07-06T17:04:57.193

3More than type safety you want logical correctness - sometimes you want things to be truthy when == disagrees. – rpjohnst – 2011-09-13T21:14:15.830

89

In JavaScript it means of the same value and type.

For example,

4 == "4" // will return true

but

4 === "4" // will return false 

Dimitar

Posted 2008-12-11T14:19:49.123

Reputation: 2 025

78

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

var a = 1;
var b = "1";

if (a == b) //evaluates to true as a and b are both 1
{
    alert("a == b");
}

if (a === b) //evaluates to false as a is not the same type as b
{
    alert("a === b");
}

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.

Doctor Jones

Posted 2008-12-11T14:19:49.123

Reputation: 17 213

Here is a detailed article on comparison of === vs == – Zaheer Ahmed – 2014-01-04T16:56:28.693

71

It checks if same sides are equal in type as well as value.

Example:

'1' === 1 // will return "false" because `string` is not a `number`

Common example:

0 == ''  // will be "true", but it's very common to want this check to be "false"

Another common example:

null == undefined // returns "true", but in most cases a distinction is necessary

vsync

Posted 2008-12-11T14:19:49.123

Reputation: 44 644

7also, 'string' !== 'number' – Homer – 2012-01-06T19:34:54.140

69

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:

'0' == false // true

Things get really weird with arrays.

[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true

Then weirder with strings

[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!

It get's worse:

When is equal not equal?

let A = ''  // empty string
let B = 0   // zero
let C = '0' // zero string

A == B // true - ok... 
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!

Let me say that again:

(A == B) && (B == C) // true
(A == C) // **FALSE**

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:

function isEqual(x, y) { // if `==` were a function
    if(typeof y === typeof x) return y === x;
    // treat null and undefined the same
    var xIsNothing = (y === undefined) || (y === null);
    var yIsNothing = (x === undefined) || (x === null);

    if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);

    if(typeof y === "function" || typeof x === "function") {
        // if either value is a string 
        // convert the function into a string and compare
        if(typeof x === "string") {
            return x === y.toString();
        } else if(typeof y === "string") {
            return x.toString() === y;
        } 
        return false;
    }

    if(typeof x === "object") x = toPrimitive(x);
    if(typeof y === "object") y = toPrimitive(y);
    if(typeof y === typeof x) return y === x;

    // convert x and y into numbers if they are not already use the "+" trick
    if(typeof x !== "number") x = +x;
    if(typeof y !== "number") y = +y;
    // actually the real `==` is even more complicated than this, especially in ES6
    return x === y;
}

function toPrimitive(obj) {
    var value = obj.valueOf();
    if(obj !== value) return value;
    return obj.toString();
}

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.

Luis Perez

Posted 2008-12-11T14:19:49.123

Reputation: 22 781

64

Javascript execution flow diagram for strict equality / Comparison '==='

Javascript strict equality

Javascript execution flow diagram for non strict equality / comparison '=='

Javascript non equality

Samar Panda

Posted 2008-12-11T14:19:49.123

Reputation: 2 515

I don't understand why the string arrow is pointing to the big gray box, is it supposed to mean the interrupter is casting the string to a number? – vsync – 2017-02-11T13:26:09.453

@vsync It points to the string option within the grey box i.e string -> # || NaN. Javascript is not a type-script language i.e basically it can have any type of variable. So, it is pointed to that grey box. – Samar Panda – 2017-02-12T06:56:21.787

I simply asked if it is for casting purposes since the string is supposed to be compared to a type number, so the interrupter looks at what the string should be compared to and cast the string accordingly? – vsync – 2017-02-12T08:44:48.897

The big gray box is what ToNumber would return when given different types, so if it is given a string it will only choose the last option (and convert it to a number). == uses ToNumber only in the cases string == number or boolean == anything above (and only on the string/boolean). This means == will never convert undefined or null even though they are in the gray box. (For any combination of either undefined or null or both, == will always return true. Also, whether a value is on the left or right side doesn't matter, == (and ===) will return the same result.) – user2033427 – 2018-03-07T05:54:22.670

52

JavaScript === vs == .

0==false   // true
0===false  // false, because they are of a different type
1=="1"     // true, auto type coercion
1==="1"    // false, because they are of a different type

user2496033

Posted 2008-12-11T14:19:49.123

Reputation:

51

It means equality without type coercion type coercion means JavaScript do not automatically convert any other data types to string data types

0==false   // true,although they are different types

0===false  // false,as they are different types

2=='2'    //true,different types,one is string and another is integer but 
            javaScript convert 2 to string by using == operator 

2==='2'  //false because by using === operator ,javaScript do not convert 
           integer to string 

2===2   //true because both have same value and same types 

Pop Catalin

Posted 2008-12-11T14:19:49.123

Reputation: 41 595

46

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 ('\t\r\n' == 0) is true.

Constantin

Posted 2008-12-11T14:19:49.123

Reputation: 20 806

1Agree, but thousand "===" means also 10 thousands of code lines else so 1kb more or less... ;) – Jonny – 2016-09-28T18:32:51.420

f your that concerned about size then just swap all your == with ===, then use a regexp wrapped in av eval to switch it back – None – 2017-04-23T03:30:55.027

4Not always true. With gzip compression, the difference would be almost negligible. – Daniel X Moore – 2009-06-22T23:43:15.070

42

The equal comparison operator == is confusing and should be avoided.

If you HAVE TO live with it, then remember the following 3 things:

  1. It is not transitive: (a == b) and (b == c) does not lead to (a == c)
  2. It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
  3. In case of doubt, learn by heart the following truth table:

EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT

  • Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*

** STRANGE: note that any two values on the first column are not equal in that sense.**

''       == 0 == false   // Any two values among these 3 ones are equal with the == operator
'0'      == 0 == false   // Also a set of 3 equal values, note that only 0 and false are repeated
'\t'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

null == undefined  // These two "default" values are not-equal to any of the listed values above
NaN                // NaN is not equal to any thing, even to itself.

CuongHuyTo

Posted 2008-12-11T14:19:49.123

Reputation: 988

35

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).

enter image description here

You can easily test it. Paste following code in an HTML file and open it in browser

<script>

function onPageLoad()
{
    var x = "5";
    var y = 5;
    alert(x === 5);
};

</script>

</head>

<body onload='onPageLoad();'>

You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.

Aniket Thakur

Posted 2008-12-11T14:19:49.123

Reputation: 40 617

35

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.

Sean

Posted 2008-12-11T14:19:49.123

Reputation: 1 102

Here is a detailed article on comparison of === vs == – Zaheer Ahmed – 2014-01-04T16:56:06.177

32

=== operator checks the values as well as the types of the variables for equality.

== operator just checks the value of the variables for equality.

Niraj CHoubey

Posted 2008-12-11T14:19:49.123

Reputation: 389

30

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:

$a = 0;

Then:

$a==0; 
$a==NULL;
$a==false;

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:

$a = 0;

$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false

Daniel

Posted 2008-12-11T14:19:49.123

Reputation: 782

3In JavaScript, this is completely wrong and wrongly incomplete. 0 != null. -1 – Ry- – 2013-05-06T03:07:17.943

29

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.

ashes

Posted 2008-12-11T14:19:49.123

Reputation: 461

28

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:

123=='123'   //will return true, because JS convert integer 123 to string '123'
             //as we used '==' operator 

123==='123' //will return false, because JS do not convert integer 123 to string 
            //'123' as we used '===' operator 

Amit

Posted 2008-12-11T14:19:49.123

Reputation: 565

25

A simple example is

2 == '2'  -> true, values are SAME because of type conversion.

2 === '2'  -> false, values are NOT SAME because of no type conversion.

Vikas

Posted 2008-12-11T14:19:49.123

Reputation: 3 023

23

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.

var a = [1, 2, 3];  
var b = [1, 2, 3];  
console.log(a == b)  // false  
console.log(a === b) // false  

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.

Harry He

Posted 2008-12-11T14:19:49.123

Reputation: 978

22

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':

if( value == null ){
    // value is either 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.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

mar10

Posted 2008-12-11T14:19:49.123

Reputation: 8 714

22

From the core javascript reference

=== Returns true if the operands are strictly equal (see above) with no type conversion.

Paul Butcher

Posted 2008-12-11T14:19:49.123

Reputation: 6 392

21

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

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...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...

Thomas Hansen

Posted 2008-12-11T14:19:49.123

Reputation: 4 373

10 == null is false. – Garrett – 2014-01-13T00:25:19.183

20

Equality comparison:

Operator ==

Returns true, when both operands are equal. The operands are converted to the same type before being compared.

>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true

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.

>>> 1 === '1'
false
>>> 1 === 1
true

user2601995

Posted 2008-12-11T14:19:49.123

Reputation: 3 171

18

*Operators === vs == *

1 == true    =>    true
true == true    =>    true
1 === true    =>    false
true === true    =>    true

Mr.G

Posted 2008-12-11T14:19:49.123

Reputation: 1 738

18

null and undefined are nothingness, that is,

var a;
var b = null;

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.

Enter image description here

This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.

vivek_nk

Posted 2008-12-11T14:19:49.123

Reputation: 1 343

17

Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.

As the conclusion states:

"Use three equals unless you fully understand the conversions that take place for two-equals."

http://dorey.github.io/JavaScript-Equality-Table/

Christian Hagelid

Posted 2008-12-11T14:19:49.123

Reputation: 6 899

16

JavaScript has both strict and type–converting comparisons. A strict comparison (e.g., ===) is only true if the operands are of the same type. The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison.

  • The equality (==) operator converts the operands if they are not of the same type, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

    Syntax:

    x == y

    Examples:

    3 == 3     // true
    "3" == 3   // true
    3 == '3'   // true
    
  • The identity/strict equality(===) operator returns true if the operands are strictly equal (see above) with no type conversion.

    Syntax:

    x === y

    Examples:

    3 === 3 // true

For reference: Comparison operators (Mozilla Developer Network)

garakchy

Posted 2008-12-11T14:19:49.123

Reputation: 405

15

If you are making a web application or a secured page you should always use (only when possible)

===

because it will will check if it is the same content and if it is the same type!

so when someone enters:

var check = 1;
if(check == '1') {
    //someone continued with a string instead of number, most of the time useless for your webapp, most of the time entered by a user who does not now what he is doing (this will sometimes let your app crash), or even worse it is a hacker searching for weaknesses in your webapp!
}

but with

var check = 1;
if(check === 1) {
    //some continued with a number (no string) for your script
} else {
    alert('please enter a real number');
}

a hacker will never get deeper in the system to find bugs and hack your app or your users

my point it is that the

===

will add more security to your scripts

of course you can also check if the entered number is valid, is a string, etc.. with other if statements inside the first example, but this is for at least me more easier to understand and use

The reason I posted this is that the word 'more secure' or 'security' has never been said in this conversation (if you look at iCloud.com it uses 2019 times === and 1308 times ==, this also means that you sometimes have the use == instead of === because it will otherwise block your function, but as said in the begin you should use === as much as possible)

Sake Salverda

Posted 2008-12-11T14:19:49.123

Reputation: 247

12

=== cares if the objects are the same. Therefore, new String("Hello world") === "Hello world" returns false. However, == does not care about if the objects are the same; it just simply converts one argument into the other's type: if conversion is not possible, return false. Then new String("Hello world") == "Hello world" returns true instead of false.

hopper

Posted 2008-12-11T14:19:49.123

Reputation: 19

12

My reasoning process using emacs org-mode and node.js to run a test.

| use =      | '' | '0' | false | 'false' | undefined | null | ' \t\r\n ' |
| ''         | x  | f   | t     | f       | f         | f    | f          |
| '0'        |    | x   | t     | f       | f         | f    | f          |
| false      |    |     | x     | f       | f         | f    | t          |
| 'false'    |    |     |       | x       | f         | f    | f          |
| undefined  |    |     |       |         | x         | t    | f          |
| null       |    |     |       |         |           | x    | f          |
| ' \t\r\n ' |    |     |       |         |           |      | x          | 



| use ===    | '' | '0' | false | 'false' | undefined | null | ' \t\r\n ' |
| ''         | x  | f   | f     | f       | f         | f    | f          |
| '0'        |    | x   | f     | f       | f         | f    | f          |
| false      |    |     | x     | f       | f         | f    | f          |
| 'false'    |    |     |       | x       | f         | f    | f          |
| undefined  |    |     |       |         | x         | f    | f          |
| null       |    |     |       |         |           | x    | f          |
| ' \t\r\n ' |    |     |       |         |           |      | x          |

My test script below: run > node xxx.js

var rowItems = ['', '0', false, 'false', undefined, null, ' \t\r\n ']
var colItems = rowItems

for(var i = 0; i < rowItems.length; i++) {
    for (var j = 0; j < colItems.length; j++) {
        var r = (rowItems[i] === colItems[j]) ? true : false;
        console.log(rowItems[i] + " = " + colItems[j] + " " + r + " [" + i + "] ==> [" + j + "]")
    };
}

CodeFarmer

Posted 2008-12-11T14:19:49.123

Reputation: 1 636

Shouldn't it be use == instead of use = in your first table? – le_m – 2017-12-03T02:11:44.803

@le_m === is more strict then =, therefore it is in right order not the other way around. – CodeFarmer – 2017-12-04T04:29:16.560

No, I meant the single = should be a double ==. The single = is the assignment operator. – le_m – 2017-12-04T04:49:34.680

11

The javascript is a weakly typed language i.e. without any data-types as there in C,c++ eg. int, boolean, float etc. thus a variable can hold any type of value, that why these special comparison operators are there

Eg

var i = 20;var j = "20";

if we apply comparison operators these variables result will be

i==j //result is true

or

j != i//result is false

for that we need a special comparison operators which checks for the value as well as for the data type of the variable

if we do

i===j //result is false

Akshay Khale

Posted 2008-12-11T14:19:49.123

Reputation: 3 778

9

Different's Between = , = = , = = =

  • = operator Used to just assign the value.
  • = = operator Used to just compares the values not datatype
  • = = = operator Used to Compare the values as well as datatype.

RïshïKêsh Kümar

Posted 2008-12-11T14:19:49.123

Reputation: 3 159

7

== operator just compares the values not datatype

=== operator compare the values with comparison of its datatype

eg.

1 == "1" //true

1 === "1" //false

"===" operator used in languages which performs automatic type cast eg. PHP, Javascript. "===" operator helps to prevent unexpected comparison caused by automatic typecast.

Sharad Kale

Posted 2008-12-11T14:19:49.123

Reputation: 495

6

always use '===' and you will avoid thousand of mistakes. nowadays using triple equality is more preferable by different style guides, because it compares taking into account type of operands.

Alexandr

Posted 2008-12-11T14:19:49.123

Reputation: 2 682

5

Yes, there is a big difference between equality == and identity === operators.
Usually the identity operator performs faster, because no types conversion is done. But if the values are of the same type, you'll see no difference.
Check my post The legend of JavaScript equality operator, which explains the details, including the types conversion & comparison algorithms, with a lot of examples.

Dmitri Pavlutin

Posted 2008-12-11T14:19:49.123

Reputation: 9 879

5

One unmentioned reason to use === - is in the case that you are co-existing with / cross-compiling to/from coffee-script. From The Little Book on CoffeeScript...

The weak equality comparison in JavaScript has some confusing behavior and is often the source of confusing bugs.

The solution is to instead use the strict equality operator, which consists of three equal signs: ===. It works exactly like the normal equality operator, but without any type coercion. It's recommended to always use the strict equality operator, and explicitly convert types if needs be.

If you are regularly converting to and from coffee-script, you should just use ===. In fact, the coffee-script compiler will force you to...

CoffeeScript solves this by simply replacing all weak comparisons with strict ones, in other words converting all == comparators into ===. You can't do a a weak equality comparison in CoffeeScript, and you should explicitly convert types before comparing them if necessary.

Alex Gray

Posted 2008-12-11T14:19:49.123

Reputation: 11 311

3

Strict equality is for the most part better

The fact that Javascript is a loosely typed language needs to be in the front of your mind constantly as you work with it. As long as the data structure is the same there really is no reason as to not use strict equality, with regular equality you often have an implicit conversion of values that happens automatically, this can have far-reaching effects on your code. It is very easy to have problems with this conversion seeing as they happen automatically.

With strict equality there is no automatic implicit conversion as the values must already be of the correct data structure.

Neil Meyer

Posted 2008-12-11T14:19:49.123

Reputation: 176

1

Javascript is loosely typed just like php is,

var x = "20";
var y =20;

if (x===y) // false

This will always give you a false because even though the values of the variables are the same, the data types are not

One is string the the other is int

If(x==y)//true

This however just checks if the content is the same, regardless of the data types...

I dont want to say the values are equal because a string value cannot be equal to an int value logically

yanguya995

Posted 2008-12-11T14:19:49.123

Reputation: 105

1

First, some terminology about Javascript string equals: Double equals is officially known as the abstract equality comparison operator while triple equals is termed the strict equality comparison operator. The difference between them can be summed up as follows: Abstract equality will attempt to resolve the data types via type coercion before making a comparison. Strict equality will return false if the types are different. Consider the following example:

console.log(3 == "3"); // true
console.log(3 === "3"); // false.
console.log(3 == "3"); // true
console.log(3 === "3"); // false.

Using two equal signs returns true because the string “3” is converted to the number 3 before the comparison is made. Three equal signs sees that the types are different and returns false. Here’s another:

console.log(true == '1'); // true
console.log(true === '1'); // false
console.log(true == '1'); // true
console.log(true === '1'); // false

Again, the abstract equality comparison performs a type conversion. In this case both the boolean true and the string ‘1’ are converted to the number 1 and the result is true. Strict equality returns false.

If you understand that you are well on your way to distinguishing between == and ===. However, there’s some scenarios where the behavior of these operators is non intuitive. Let’s take a look at some more examples:

console.log(undefined == null); // true
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.
console.log(undefined == null); // true     
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.

console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false
console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false

The example below is interesting because it illustrates that string literals are different from string objects.

console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false
console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false

Akintunde-Rotimi

Posted 2008-12-11T14:19:49.123

Reputation: 3 656

1

Use === if you want to compare couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you, if you using ==, you basically don't care about the type and in many cases you could face issues with loose equality comparison.

Strict equality using ===

Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. Otherwise, if the values have the same type and are not numbers, they're considered equal if they have the same value. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0.

var num = 0;
var obj = new String('0');
var str = '0';

console.log(num === num); // true
console.log(obj === obj); // true
console.log(str === str); // true

console.log(num === obj); // false
console.log(num === str); // false
console.log(obj === str); // false
console.log(null === undefined); // false
console.log(obj === null); // false
console.log(obj === undefined); // false


Loose equality using ==

Loose equality compares two values for equality, after converting both values to a common type. After conversions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions).

var num = 0;
var obj = new String('0');
var str = '0';

console.log(num == num); // true
console.log(obj == obj); // true
console.log(str == str); // true

console.log(num == obj); // true
console.log(num == str); // true
console.log(obj == str); // true
console.log(null == undefined); // true

// both false, except in rare cases
console.log(obj == null);
console.log(obj == undefined);

Alireza

Posted 2008-12-11T14:19:49.123

Reputation: 43 514

1

The reason it suggest to replace == with === is that the === operator is more reliable than ==. In our context reliable means === also goes for type checking. Considering the best programming practices we should always choose more reliable feature over less reliable one. Again whenever we think about exactly equal to operator most of the time, we are by default consider the type should be same. As === provides the same, we should go for it.

Narendra Kalekar

Posted 2008-12-11T14:19:49.123

Reputation: 39

1

The dilemma of "Should I use == or === in JavaScript comparison" is equal or analogous to a question of: "Should I use a 'spoon' or a 'fork' for eating.

The only reasonable answer to this question is that

  1. You should use Dynamic Type comparison e.g.:== for loose Type comparisons.
  2. You should use Static Type comparison e.g.:=== for strong Type comparisons.

That's because they are not the same. They don't have the same purpose and are not meant to be used for the same purpose.

Of course both 'forks' and 'spoons' are meant for 'eating', but you will chose to use them accordingly to what you've been served to eat.

Meaning: you'll resolve to using a 'spoon' i.e.: == for having a 'soup', and / or the 'fork' i.e.: === for picking.

Asking if it is better to use a "fork" or a "spoon" for "eating" - is equall to asking if it is better to use a static [===] versus dynamic [==] eq., op. in JS. Both questions are equally wrong and reflect a very narrow or shallow understanding of the subject in question.

Bekim Bacaj

Posted 2008-12-11T14:19:49.123

Reputation: 2 446

0

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

Saw this in one of the answers. a and b are not really the same type in this case, if you will check typeof(a) you will get 'object' and typeof(b) is 'string'.

Orri Scott

Posted 2008-12-11T14:19:49.123

Reputation: 29

-2

1 == "1"    =>    true(define)
true === "true"    => false(undefined compare the type of variable)
Case 1
if(true === "true"){
  echo 'true'
}else{
 echo 'false undefined'
}
Ans :- false undefined because case 1 is check data type also with ===  
Case 2
if(1 == "1"){
  echo 'true define'
}else{
 echo 'false undefined'
}
Ans :- true define undefined because case 2 is not check data type with ==

vikram mohod

Posted 2008-12-11T14:19:49.123

Reputation: 45