Compare Two Strings in JavaScript

May 28, 2019

JavaScript makes comparing strings easy. First, to compare if two strings are exactly equal, use ===. Do not use ==.

const str1 = '1st string';
const str2 = str1;
const str3 = '2nd string';

str1 === str2; // true
str1 === str3; // false

// Always use `===`, because `==` can have some surprises
'1' == 1; // true
'2' == 2; // true

< and >

Using < and > compares strings lexicographically according to Unicode sort order. That means digits are always < uppercase letters, and uppercase letters are always < lowercase letters.

const str1 = '0';
const str2 = 'A';
const str3 = 'Z';
const str4 = 'a';

str1 < str2; // true
str2 < str3; // true
str3 < str4; // true

When comparing strings with length greater than 1, JavaScript compares character by character. If both strings start with the same character, JavaScript compares the 2nd characters of each string. The end of a string is always < any character.

// Empty string '' is `<` all other strings
const str1 = '';
const str2 = 'A';
const str3 = 'A1';
const str4 = 'Z0';

str1 < str2; // true
str2 < str3; // true
str3 < str4; // true

The < and > operators return false when comparing a string to a non-string:

1 < 'A'; // false
'A' < 1; // false

null < 'A'; // false
'A' < null; // false

undefined < 'A'; // false
'A' < undefined; // false

Sorting

By default, the Array#sort() function converts all values in an array to strings and then sorts them in Unicode sort order. The sort() function puts null and undefined values at the end of the array.

1 < 'A'; // false
'A' < 1; // false

null < 'A'; // false
'A' < null; // false

undefined < 'A'; // false
'A' < undefined; // false

<= and >=

Be careful when using <= and >=, because these use the same type coercion that == does.

'1' <= 1; // true

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!