By JSS


2010-08-27 17:37:55 8 Comments

What is the correct way to check for equality between Strings in JavaScript?

9 comments

@Kamil Kiełczewski 2020-08-03 19:44:13

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

enter image description here

a === b (and its negation !==)

enter image description here

@STW 2010-08-27 17:39:09

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook


Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

@Marcel Korpel 2010-08-27 17:43:13

It's not necessary when you're sure both operands are string, e.g., when using if (typeof foo == "string")

@STW 2010-08-27 17:44:02

@Marcel -- you're correct, but it's much better to always use the === operator and never have to worry about the "am I really, totally, 100% certain that == will behave how I think it will?"

@Cristian Sanchez 2010-08-27 17:55:21

There are certain cases where it will always be a string, making === and its (infinitesimal) performance impact unnecessary. One is typeof, which is guaranteed to return a string. Another case off the top of my head is when you are iterating over a set of keys in an object -- of course, it also matters what you're comparing it to. These are cases where you don't have to "think" because it's guaranteed. I think for a beginner, it's not a bad idea to use ===, but if you're experienced and know the spec well, you can forgo using === without risk.

@MooGoo 2010-08-27 18:40:51

And there are also cases where type coercion is a good thing. An example would be when comparing user input from some form element, which is always retrieved as a string, to a number. There are others. Treating == and type coercion as some kind of evil bug is bad practice I think.

@Marcel Korpel 2010-08-27 19:28:10

@STW – one example why Crockford is not the alpha and omega of JavaScript, is his advice not to use unary increment/decrement (++/--).

@MooGoo 2010-08-27 19:35:22

And never use ++ or -- or single line if/else statements or continue or the new operator or any other number of perfectly legitimate code practices that Crockford has deemed "harmful". And of course never ever even consider thinking about using eval or with even if their pitfalls are well understood. And have you seen the next version of JS? Stricter syntax and a handful of helper functions, some which have been floating around for years, is about all we get after all this time. The syntax has not evolved at all. If Crockford is behind this, then it has been a bad thing.

@Marcel Korpel 2010-08-28 11:13:42

Oh yes, but that's not dependent on Stack Overflow. But your corrections improve this answer, so +1.

@L0j1k 2013-03-28 01:55:32

Crockford has really good ideas and valid reasons for his ideas, but at the end of the day, YOU are the programmer. It's always good to take your cigar-smoking methodology advice from an expert, but don't forget to think for yourself. Smoke it backwards if that's what suits your situation.

@PositiveGuy 2013-05-30 18:28:04

I think this is not 100% true for strings. I think one of them is not case sensitive while the other is...

@STW 2013-05-30 18:35:54

@CoffeeAddict -- a quick test in JSFiddle appears to disagree. They are both case-sensitive: jsfiddle.net/st2EU

@amn 2019-05-13 09:07:36

I have been writing JavaScript for years, and every time I see people use === in places where you'd obviously expect the good old ==, it always surprises me negatively. And surprises like this when reading code are invariably bad, no matter how JavaScript's peculiarities are, which I won't deny are many, compared to another language where use of == would be obvious. So for the sake of not tripping up people reading your code, and rest assured if == doesn't work for you chances are you have much bigger problems than you thought -- just use == and stop being a smart-ass.

@amn 2019-05-13 09:10:12

My point is contrary to the advice presented in this answer -- if you aren't really sure how === works, don't use it and even if you do, consider people trying to understand your logic when reading your code -- stick to the much more familiar to most == operator. === is only ever really useful in really fundamental levels of code where you'd need actual object reference comparison for things to work. If JavaScript were designed differently, perhaps one could have avoided this debate altogether, alas it is not the case, but fact of the matter is that === is tripping people up.

@E_net4 the account reporter 2019-05-13 10:00:06

@amn Many modern conventions actually advise developers to stick to the strict equality operator === (e.g. ESLint's eqeqeq rule). The way I see it, the behavior of == making implicit conversions before the actual comparison is what trips people up. When coming from different languages, == is only familiar in syntax, not in semantics. Nevertheless, that seems to be just another opinion, and your choice of words here was too strong just for exposing an opinion.

@Andrii M4n0w4R 2020-07-23 11:05:35

The question has a specific context: "correct way to check for equality between Strings in JavaScript". And this answer, as it is now, does a general discussion about difference between == and ===, "good or bad" parts of Javascript, has some links to additional info, but states exactly nothing about correct way of string equality check. -1 for losing the specific string context of a question. Have a look for @Anurag answer.

@Nagibaba 2020-02-25 10:25:58

Considering that both strings may be very large, there are 2 main approaches bitwise search and localeCompare

I recommed this function

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}

@Muhammad Usman 2018-07-04 12:33:12

String Objects can be checked using JSON.stringyfy() trick.

var me = new String("me");
var you = new String("me");
var isEquel = JSON.stringify(me) === JSON.stringify(you);
console.log(isEquel);

@Basheer AL-MOMANI 2016-07-27 10:52:37

what led me to this question is the padding and white-spaces

check my case

 if (title === "LastName")
      doSomething();

and title was " LastName"

enter image description here

so maybe you have to use trim function like this

var title = $(this).text().trim();

@Akitha_MJ 2019-01-08 18:15:00

Thanks same here I used .toString().trim() in Typescript

@Khorram Bin Salim Khondkar 2018-10-24 20:42:22

I came up with a alternative solution during testing. you can use function on the string prototype.

String.prototype.betwenStr = function(one){

return JSON.stringify(new String(this)) === JSON.stringify(new String(one));

}


 //call it
 "hello world".betweenStr("hello world"); //returns boolean 
 //value

works fine in chrome browsers

@Nick 2018-10-25 04:07:15

The question asks how to check if "hello world" = "hello world", not how to check if "hello world" is a string.

@JJJ 2018-10-25 17:40:48

This is just silly. You've created a Rube Goldberg version of ==.

@Yılmaz Durmaz 2019-08-15 14:13:53

Hi OP, your edit is completely different in its spiritual part, and your answer has already got too many downvotes. I urge you please to remove this answer and post a new one with your edited version

@akelec 2017-05-02 13:41:38

Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

I have lost hours trying to figure out what is wrong. Hope this will help to someone!

@Niko 2018-02-12 07:41:31

Thanks a lot. It is strange to me though, because I made sure there was no whitespace to the left or right and still this was the only way to solve my problem. Maybe it is related to the internal representation of a string?

@stwr667 2018-02-19 12:41:11

Thanks @akelec!! @Niko, it was likely due to the Zero-Width-Space character which is invisible to the naked eye. See en.wikipedia.org/wiki/Zero-width_space. Even though this character has its purposes, many developers resent its existence!

@drzounds 2018-10-04 03:29:13

Thank you that was frustrating since the equality check in my if was failing yet I saw no whitespace when inspecting while debugging.

@Sopalajo de Arrierez 2019-11-26 21:27:12

A common problem when loading a variable from a text file (i.e: using fetch). Thanks a lot.

@akelec 2019-11-26 22:34:54

@SopalajodeArrierez, exactly, there is mostly a space or a carriage return at the end of string. You are welcome.

@Anayo Oleru 2020-08-08 11:28:02

This is the best answer.

@Abhishek 2015-05-02 19:11:31

There are actually two ways in which strings can be made in javascript.

  1. var str = 'Javascript'; This creates a primitive string value.

  2. var obj = new String('Javascript'); This creates a wrapper object of type String.

    typeof str // string
    typeof obj // object

So the best way to check for equality is using the === operator because it checks value as well as type of both operands.

If you want to check for equality between two objects then using String.prototype.valueOf is the correct way.

new String('javascript').valueOf() == new String('javascript').valueOf()

@Anurag 2010-08-27 17:40:08

If you know they are strings, then there's no need to check for type.

"a" == "b"

However, note that string objects will not be equal.

new String("a") == new String("a")

will return false.

Call the valueOf() method to convert it to a primitive for String objects,

new String("a").valueOf() == new String("a").valueOf()

will return true

@JSS 2010-08-27 17:41:11

you mean new String("a") == new String("a") will return false? what about new String("a") === new String("b")?

@Anurag 2010-08-27 17:43:18

thank for that JSS, two string objects will never be equal unless they are the same object regardless of the value.

@Matthew Crumley 2010-08-27 18:27:01

@JSS: Additionally, new String("a") == "a" is true (but wouldn't be with ===), because the left hand side will be converted into a primitive string value.

@palswim 2010-08-27 18:39:18

@JSS: new String("a") == new String("a"), new String("a") === new String("b"), new String("a") === new String("a") will all return false, since you're dealing with references to objects of the String class, not primitives of type string.

@Brigand 2013-08-30 16:31:30

Just to clarify this for anyone reading it. new String(foo) creates a string object, and String(foo) converts foo to a string primitive.

@Periata Breatta 2016-09-30 07:28:08

@FakeRainBrigand - clear as mud, but that's what javascripts about, isn't it?

Related Questions

Sponsored Content

97 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 7140302 View
  • 8653 Score
  • 97 Answer
  • Tags:   javascript arrays

54 Answered Questions

40 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

47 Answered Questions

[SOLVED] How can I check for an empty/undefined/null string in JavaScript?

22 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

63 Answered Questions

[SOLVED] What is the difference between String and string in C#?

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

3 Answered Questions

67 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

Sponsored Content