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!
How to Install Node on Windows, macOS and Linux
Getting Started with Express
Create an RSS Reader in Node
How to Serve Static Files with Nginx and Docker
How to deploy a Deno app using Docker
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Handlebars.js
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting Started with Moment.js
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Using Axios to Pull Data from a REST API
