Borislav Hadzhiev
Fri Oct 15 2021·2 min read
Photo by Dan Gold
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.
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.
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.
false
, if the values on the left and right hand side are of different type.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 (==).
console.log(123 == '123'); // 👉️ true
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.
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.
const str1 = 'ABC'; const str2 = 'abc'; // 👇️ true console.log(str1.toLowerCase() === str2.toLowerCase());
Here are some examples using the negated strict equality operator (!==).
console.log('a' !== 'A'); // 👉️ true console.log('a' !== 'a'); // 👉️ false console.log('a' !== ' a'); // 👉️ true