How to Check if Two Values are Not Equal in JavaScript
A fundamental operation in any programming language is comparing two values to see if they are different. In JavaScript, the primary tool for this is the strict inequality operator (!==). Using the correct operator is essential for writing predictable, bug-free code, especially given JavaScript's distinction between strict and loose comparisons.
This guide will teach you how to use the !== operator, explain why it is the recommended best practice over the loose inequality operator (!=), and cover important edge cases like case-sensitivity and comparing objects.
The Core Method: Strict Inequality (!==)
The !== operator is the most reliable way to check if two values are not equal. It returns true if the values are not equal or are not of the same type, and false if they are.
Problem: you have two strings and need to confirm they are different.
// Problem: How do we check if these two strings are different?
const stringA = 'hello';
const stringB = 'world';
Solution: use the !== operator for a direct and readable comparison.
const stringA = 'hello';
const stringB = 'world';
const stringC = 'hello';
if (stringA !== stringB) {
console.log(`'${stringA}' and '${stringB}' are not equal.`);
} else {
console.log(`'${stringA}' and '${stringB}' are equal.`);
}
// Output: 'hello' and 'world' are not equal.
console.log(stringA !== stringC); // Output: false
Why Strict Inequality is Recommended (vs. Loose Inequality !=)
JavaScript has two inequality operators, and the difference is critical.
- Strict Inequality (
!==): Returnstrueif the operands are not equal and/or are not of the same type. It does not perform type coercion. - Loose Inequality (
!=): Returnstrueif the operands are not equal after attempting to convert them to a common type. This is called type coercion and can lead to confusing results.
The Problem with Loose Inequality
Type coercion can hide bugs and make code unpredictable.
// Problem: These values look different, but `!=` says they are equal.
const num = 5;
const str = '5';
if (num != str) {
console.log('The values are not equal.');
} else {
console.log('The values are considered equal.');
}
// Output: The values are considered equal. (This is confusing!)
This happens because the != operator converts the string '5' to the number 5 before comparing.
Solution: Always Use Strict Inequality
The !== operator avoids this confusion by checking the type first.
const num = 5;
const str = '5';
if (num !== str) {
console.log('The values are not equal because their types are different.');
} else {
console.log('The values are equal.');
}
// Output: The values are not equal because their types are different.
Best Practice: Always use strict equality (===) and strict inequality (!==) to avoid unexpected bugs from type coercion.
Common Pitfalls and Edge Cases
Case-Sensitivity in Strings
String comparisons in JavaScript are case-sensitive. 'Hello' and 'hello' are not considered equal.
console.log('Hello' !== 'hello'); // Output: true
Objects and Arrays (Reference Types)
Objects and arrays are compared by reference, not by their content. Two different arrays or objects are never equal, even if they contain the exact same values.
console.log([] !== []); // Output: true
console.log({} !== {}); // Output: true
This is because each {} or [] creates a new, unique object in memory.
The NaN Anomaly
NaN (Not a Number) is a special value in JavaScript that is not equal to anything, including itself.
console.log(NaN !== NaN); // Output: true
Best Practice: To check if a value is NaN, do not compare it to NaN. Instead, use the built-in Number.isNaN() function.
console.log(Number.isNaN(NaN)); // Output: true
Practical Example: Case-Insensitive String Comparison
The most common use case that requires extra care is case-insensitive comparison. Since !== is case-sensitive, you must first normalize the strings to the same case (typically lowercase) before comparing them.
function areStringsDifferent(str1, str2) {
// Convert both strings to lowercase before comparing
return str1.toLowerCase() !== str2.toLowerCase();
}
// Example Usage:
const userInput = 'JavaScript';
const storedValue = 'javascript';
if (areStringsDifferent(userInput, storedValue)) {
console.log('The strings are different.');
} else {
console.log('The strings are considered the same (case-insensitively).');
}
// Output: The strings are considered the same (case-insensitively).
Conclusion
Checking for inequality is a fundamental operation, and using the correct tool is key to writing reliable JavaScript code.
- The strict inequality operator (
!==) is the recommended best practice for all comparisons. It provides predictable results by not performing type coercion. - Avoid the loose inequality operator (
!=), as its type coercion can lead to confusing bugs. - Be mindful of edge cases: string comparisons are case-sensitive, and objects/arrays are compared by reference.
By defaulting to !== in your code, you will write more robust, predictable, and maintainable applications.