How to compare Strings in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

banner

Photo by Dan Gold

Compare Strings in JavaScript #

Use the strict equality (===) operator to compare strings, e.g. 'string' === 'string'. The operator checks if the values on the left and right hand side are equal. The strict equality operator returns true if the values are equal and false otherwise.

index.js
const str1 = 'abc'; const str2 = 'abc'; if (str1 === str2) { console.log('✅ Strings are equal'); } else { console.log('⛔️ Strings are NOT equal'); }

We use the strict equality (===) operator to check if two strings are equal.

This is the most common and straight forward way to compare strings in JavaScript.

If you want to check if two strings are not equal use the negated form of the strict equality operator (!==) instead.

index.js
const str1 = 'abc'; const str2 = 'xyz'; if (str1 !== str2) { console.log('✅ Strings are NOT equal'); } else { console.log('⛔️ Strings are equal'); }

For two strings to be equal they must have the same characters in the same order.

Note that the strict equality operator returns false, if the values on the left and right hand side are of different type.
index.js
console.log(123 === '123'); // 👉️ false

This is because the strict equality operator (===) does not coerce the types of the values before comparing them, as opposed to the equality (==) operator.

Here's the same example, however this time we use loose equality (==).

index.js
console.log(123 == '123'); // 👉️ true
Most (if not all) of the time it's unintuitive and a bad practice to use loose equality, because it makes your code harder to read.

The loose equality (==) operator attempts to convert the left and right hand values to the same type before comparing them. This can be quite confusing and can lead to hard to track bugs.

Here are some more examples of using the strict equality (===) operator with strings.

index.js
console.log('abc' === 'abc'); // 👉️ true console.log('abc' === 'ABC'); // 👉️ false console.log('abc' === ' abc '); // 👉️ false

Notice that the strict equality operator performs a case sensitive check.

If you need to perform a case insensitive check with the strict equality operator, convert both strings to lowercase when comparing them.

index.js
const str1 = 'ABC'; const str2 = 'abc'; // 👇️ true console.log(str1.toLowerCase() === str2.toLowerCase());

Here are some examples using the negated strict equality operator (!==).

index.js
console.log('a' !== 'A'); // 👉️ true console.log('a' !== 'a'); // 👉️ false console.log('a' !== ' a'); // 👉️ true
Make sure to always use the strict equality (===) operator, because the loose equality operator (==) can lead to confusion and cause bugs in your application.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee