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


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

8/3/2020 7:45:09 PM

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


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!


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

check my case

 if (title === "LastName")

and title was " LastName"

enter image description here

so maybe you have to use trim function like this

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

Unless you really know how coercion works, you should avoid == and use the identity operator === instead. But you should read this to understand how it works.

If you use ==, you let the language do some type coercion for you, so for example:

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

As Douglas Crockford's said in his book:

It’s always better use the identity operator.


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