How to check if two Strings are not equal in JavaScript
Table of Contents
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:
JAVASCRIPTconst a = "Hello";
const b = "World";
if (a !== b) {
console.log("Strings are not equal");
} else {
console.log("Strings are equal");
}
BASHStrings 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:
JAVASCRIPTconsole.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!
- Managing PHP Dependencies with Composer
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Using Axios to Pull Data from a REST API
- Getting Started with Moon.js