Borislav Hadzhiev
Sat Mar 05 2022·2 min read
Photo by Alan Labisch
Use the strict equality operator (===) to check if two strings are equal in
TypeScript, e.g. if (str1 === str2) {}
. The strict equality operator returns
true
if the strings are equal, otherwise false
is returned.
const str1 = 'hello'; const str2 = 'hello'; if (str1 === str2) { console.log('✅ strings are equal'); } else { console.log('⛔️ strings are NOT equal'); }
We used the strict equality (===) operator to check if two TypeScript strings are equal.
The operator returns a boolean result:
true
if the values are equalfalse
if the values are not equalWhen comparing strings with the strict equality (===) operator, comparisons are case sensitive.
const str1 = 'hello'; const str2 = 'HELLO'; if (str1 === str2) { console.log('✅ strings are equal'); } else { // 👇️ this runs console.log('⛔️ strings are NOT equal'); }
If you need to make a case insensitive comparison, use the toLowercase()
method on both strings.
const str1 = 'hello'; const str2 = 'HELLO'; if (str1.toLowerCase() === str2.toLowerCase()) { // 👇️ this runs console.log('✅ strings are equal'); } else { console.log('⛔️ strings are NOT equal'); }
If you need to check if two strings are NOT equal, use the strict inequality (!==) operator.
const str1 = 'hello'; const str2 = 'world'; if (str1 !== str2) { console.log('✅ strings are equal'); } else { console.log('⛔️ strings are NOT equal'); }
The strict inequality (!==) operator returns true
if the values are not equal
and false
otherwise.
The strict equality (===) operator differs from the loose equality (==) operator in that it considers two values of different types to NOT be equal.
const str = '100'; const num = 100; // ⛔️ Error: This condition will always return 'false' // since the types 'number' and 'string' have no overlap.ts(2367) if (str == num) { console.log('✅ strings are equal'); } else { console.log('⛔️ strings are NOT equal'); }
The example above uses the loose equality operator to check if the number 100
is equal to the string '100'
.
This would evaluate to true
if ran in JavaScript, but in TypeScript, the type
checker throws an error.
It's much more intuitive to always use the strict equality (===) operator and stick to comparing values of the same type.
This means that two values of different types will never be equal, when using the strict equality operator.
It's always recommended to use the strict operators (!==, ===), because they don't try to coerce the values to the same type before comparing them and return more intuitive and easier to read results.