How to check if two Strings are not equal in JavaScript

Updated onbyAlan Morel
How to check if two Strings are not equal in JavaScript

Strings are a critical part of any programming language because of how often you need to represent text.

When you're working with multiple strings, you will need to be able to compare them, specifically to know if they are equal or not.

In this post, we will learn how to check if two strings are not equal to one another.

Checking if two strings are not equal

The best way to check if two strings are not equal is to use the strict inequality !== operator.

This operator is simple, it will return true if the two strings are not equal, and false if they are equal.

Here's an example:

JAVASCRIPT
const a = "Hello"; const b = "World"; if (a !== b) { console.log("Strings are not equal"); } else { console.log("Strings are equal"); }
BASH
Strings are not equal

The ! is what negates the result of the operator, which is the opposite of the === operator.

Let's see more examples of what the !== operator returns:

JAVASCRIPT
console.log("Hello" !== "World"); // true console.log("Hello" !== "Hello"); // false console.log("" !== ""); // false console.log(null !== null); // false console.log(undefined !== undefined); // false console.log(0 !== 0); // false console.log(1 !== 1); // false console.log(NaN !== NaN); // true console.log(Infinity !== Infinity); // false console.log(true !== true); // false console.log(false !== false); // false console.log([] !== []); // true console.log([1] !== [1]); // true console.log({} !== {}); // true

Make sure not to confuse !== with !=. The != operator is used to check if two values are not equal but it uses loose inequality.

The difference between loose and strict inequality is that for loose inequality, if the two values have different types, JavaScript will attempt to convert the values to the same type before comparing them.

With strict inequality, the two values must be of the same type or else they are automatically considered not equal.

Conclusion

In this post, we learned how to check if two strings are not equal to one another using the strict inequality operator.

While you can also use loose inequality, it is not recommended because it is not as predictable as strict inequality.

Hopefully, you learned something from this post. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.