1142

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

8
  • 7
    Is there a reason not to use == ?
    – Kendrick
    Aug 27, 2010 at 17:41
  • 30
    @Kendrick -- sure. It's type-coercion system can be incredibly unintuitive and can make errors very easy to overlook (it looks right, but can be very wrong)
    – STW
    Aug 27, 2010 at 17:42
  • 29
    @Kendrick - because {} == "[object Object]" evaluates to true, for example.
    – Chetan S
    Aug 27, 2010 at 17:48
  • 22
    somewhat annoying that String().equals() is not a method in JS... Oct 6, 2017 at 23:53
  • 2
    @AlexanderMills Why?
    – Ry-
    Oct 7, 2018 at 21:21

10 Answers 10

808
+100

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.

18
  • 8
    It's not necessary when you're sure both operands are string, e.g., when using if (typeof foo == "string") Aug 27, 2010 at 17:43
  • 40
    @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?"
    – STW
    Aug 27, 2010 at 17:44
  • 7
    @STW – one example why Crockford is not the alpha and omega of JavaScript, is his advice not to use unary increment/decrement (++/--). Aug 27, 2010 at 19:28
  • 12
    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.
    – MooGoo
    Aug 27, 2010 at 19:35
  • 5
    @CoffeeAddict -- a quick test in JSFiddle appears to disagree. They are both case-sensitive: jsfiddle.net/st2EU
    – STW
    May 30, 2013 at 18:35
265

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

6
  • 5
    thank for that JSS, two string objects will never be equal unless they are the same object regardless of the value.
    – Anurag
    Aug 27, 2010 at 17:43
  • 6
    @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. Aug 27, 2010 at 18:27
  • 6
    @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.
    – palswim
    Aug 27, 2010 at 18:39
  • 10
    Just to clarify this for anyone reading it. new String(foo) creates a string object, and String(foo) converts foo to a string primitive.
    – Brigand
    Aug 30, 2013 at 16:31
  • 12
    @FakeRainBrigand - clear as mud, but that's what javascripts about, isn't it? Sep 30, 2016 at 7:28
104

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

6
  • 19
    well at least '==' is symmetrical ... |-=)
    – Lars
    Jan 21, 2021 at 12:56
  • @Lars not exactly: if("0"==0 && 0==[]) console.log("0"==[]); Jan 21, 2021 at 15:30
  • I ment if a==b then b==a for all a and b
    – Lars
    Mar 11, 2021 at 10:50
  • @Lars it is symmetrical like you say but... it's JS :P Mar 11, 2021 at 12:12
  • 4
    The creators were playing minesweeper when deciding the == specs. 😂 Aug 28, 2022 at 4:02
88

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!

9
  • 1
    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?
    – Niko
    Feb 12, 2018 at 7:41
  • 2
    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!
    – stwr667
    Feb 19, 2018 at 12:41
  • 1
    Thank you that was frustrating since the equality check in my if was failing yet I saw no whitespace when inspecting while debugging.
    – drzounds
    Oct 4, 2018 at 3:29
  • A common problem when loading a variable from a text file (i.e: using fetch). Thanks a lot. Nov 26, 2019 at 21:27
  • This is the best answer. Aug 8, 2020 at 11:28
31

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();
3
  • 2
    Thanks same here I used .toString().trim() in Typescript
    – Akitha_MJ
    Jan 8, 2019 at 18:15
  • 1
    How is this an answer to anything? Nov 16, 2022 at 18:57
  • −1. This has nothing to do with string equality. You are talking about one way of defining string equivalence in some specific regard. You could just as well talk about a myriad of other caveats, such as invisible characters, case, or combining characters. This is off-topic. Plus, your wording is unclear. Jan 24, 2023 at 9:39
17

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()
9

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

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

2
  • You are kidding right? Did you meant iSequel ;) Just kidding... Apr 30, 2021 at 1:58
  • Although it works, it is not recommended, as it's a really time consuming operation. This solution should only be chosen if nothing else works. So, be aware in your future developments :)
    – JrmDel
    Oct 25, 2022 at 8:35
5

Strict Comparisons

To do simple comparison, use === to check for strict equality. As others stated, this has the advantages of being most efficient and reducing the chances of buggy or uncertain code. Source: MDN Web Docs: Strict Equality.

var a = "hello1";
var b = "hello2";
console.log("a === a?" + (a === a) + "|");
console.log("a === b?" + (a === b) + "|");

Alphabetical Comparisons

If you want to compare two strings to know if a string comes before or after another string, based on natural sorting, use the <, >, <=, and >= operators. Source: MDN WebDocs for <, >, <=, and >=.

    var a = "hello1";
    var b = "hello2";
    console.log("a < a?" + (a < a) + "|");
    console.log("a < b?" + (a < b) + "|");
    console.log("a > b?" + (a > b) + "|");
    console.log("b > a?" + (b > a) + "|");

2

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;
}
2

For strings, we have a supported method localCompare which is very handy in string comparison. IMO, we should just use it and doesn't need to complicate stuff.

Usage:

const a = 'Hello'
const b = 'Hell'

a.localCompare(a) // 0
a.localCompare(b) // 1
b.localCompare(a) // -1
2
  • One of the annoying things about localeCompare is that if two strings are the same, it returns a 0, meaning your code then becomes full of things like "if (!stringA.localeCompare(stringB)) ". All those not signs are ugly and, if you're not familiar with localeCompare, can make you think you're looking for a false result in the if statement instead of the true result.
    – Onychomys
    Dec 27, 2022 at 15:43
  • @Onychomys I consider best to write those tests more explicitly: if (stringA.localeCompare(stringB) === 0). What other result than 0 would you consider not annoying? Some constant such that the check would be something like if (stringA.localeCompare(stringB) === ComparisonResult.orderedSame)? Jan 24, 2023 at 9:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.