Check if two Strings are NOT equal in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

Check if two Strings are NOT equal #

Use the strict inequality (!==) operator to check if two strings are not equal to one another, e.g. a !== b. The strict inequality operator returns true if the strings are not equal and false otherwise.

index.js
const a = 'one'; const b = 'two'; if (a !== b) { console.log('โœ… strings are NOT equal'); } else { console.log('โ›”๏ธ strings are equal'); }

We used the strict inequality (!==) operator to check if two strings are not equal to one another.

The operator returns a boolean result:

  • true if the values are not equal
  • false if the values are equal

The strict inequality (!==) operator is the negation of the strict equality (===) operator.

Here are some more examples.

index.js
console.log(5 !== '5'); // ๐Ÿ‘‰๏ธ true console.log('one' !== 'one'); // ๐Ÿ‘‰๏ธ false console.log('one' !== 'ONE'); // ๐Ÿ‘‰๏ธ true console.log('' !== ' '); // ๐Ÿ‘‰๏ธ true console.log(null !== null); // ๐Ÿ‘‰๏ธ false console.log(undefined !== undefined); // ๐Ÿ‘‰๏ธ false console.log(NaN !== NaN); // ๐Ÿ‘‰๏ธ true

The strict inequality (!==) operator considers two values of different types to be different, as opposed to the loose inequality (!=) operator.

This means that two values of different types will never be equal, when using the strict inequality 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.

Notice that in the last example, the evaluation NaN !== NaN returns true. This is because NaN (not a number) is the only value in JavaScript, which is not equal to itself.

Further Reading #

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