Best way to compare strings in javascript

Strings are the one of the most used immutable data structure of javascript and there is often scenarios where we need to compare two or more strings.

Here we will checkout different optimum ways to compare strings in javascript.

Using localeCompare() to compare strings

Javascript has inbuilt method String.prototype.localeCompare() which we can use to compare two strings. It compares the given strings in current locale which is based on the language settings of the browser.

let a = '2';
let b = 2;
let c = '2';

console.log(a.localeCompare(b));
console.log(a.localeCompare(c));

String.prototype.localeCompare() compares the given two strings and returns the following result.

  • 0: If both the strings are equal.
  • 1: If first string is smaller than second string in sorted order.
  • -1: It it is greater than second string.

Greater than > and less than < comparison

We can use the > & < operator to compare order of the two strings.

let a = 'aaa';
let b = 'aab';

console.log(a < b);
console.log(a > b);
//true
//false

It compares both the strings based on the ASCII value of each characters and this is how it works.

  1. Compare the first character of both the strings.
  2. If the character from the first string is greater than the character of the second string then first string is greater else second string is greater.
  3. If the character of both string are equal, the move to the second character of the strings.
  4. Repeat the steps for each character of both the strings.
  5. If any string has less characters than the other string then one with more characters will be greater.
  6. If both are of equal length and same characters then both are equal.

Strict equality comparison

Javascript has another comparison operator === which does strict equality checking i.e it checks value and data type both. It never does type conversion unlike == operator.

let a = '2';
let b = 2;
let c = '2';

console.log(a === b);
console.log(a === c);

//false
//true

Use === operator wherever possible to avoid logical errors in your code.


Normal equality comparison

We can use == to compare two strings.

let a = 'prashant';
let b = 'yadav';
if(a == b){
  console.log('not matched');
}

//"matched"

This comparison works fine when you are just comparing strings, But its behavior changes when we compare string with other data types.

let a = '2';
let b = 2;
if(a == b){
  console.log("matched");
}

//"matched"

== converts the value to different data types while comparing, i.e numeric 2 is converted to string '2' while comparing so it becomes '2' == '2' and we get true.

Leave a Reply

Your email address will not be published. Required fields are marked *