Fastest way to test two strings for exact match in JavaScript

atreju picture atreju · Sep 3, 2013 · Viewed 46.9k times · Source

I want to compare two strings in JavaScript to test if they are exactly the same. Which would be the best (fastest) way to do this?

Right now, I'm considering either

if(string1.localeCompare(string2) == 0) {}

or simply

if(string1 == string2)

Is there a better way do to this?

Answer

Andy picture Andy · Sep 3, 2013

I would probably use strict equality if you want to check they are exactly the same, ie they're the same type too, just in case.

if (string1 === string2)