In JavaScript, comparison operators help you check if values are the same or different. Inequality operators are special tools that let you check if two values are *not* the same. You will learn about `!=` (loose inequality) and `!==` (strict inequality) and when to use each one.
Inequality Operators (!=, !==)
Inequality Operators (!=, !==)
When you write code, you often need to make decisions. These decisions depend on whether certain values are equal or not. Inequality operators are like asking, "Are these two things different?" If they are different, the answer is true. If they are the same, the answer is false.
What are Inequality Operators?
Inequality operators are symbols in programming that check if two values are not equal to each other. They return true if the values are different and false if they are the same.
Loose Inequality (`!=`)
This operator checks if values are different, but it might change their types first to make a comparison.
Strict Inequality (`!==`)
This operator checks if values are different and also if their data types are different, without changing types.
Making Decisions
Inequality operators are important for creating conditional code that runs only when certain conditions are not met.
Avoiding Bugs
Understanding these operators helps prevent unexpected behavior in your programs, especially with different data types.
Understanding Basic Inequality (`!=`)
Understanding Basic Inequality (`!=`)
The != operator means 'not equal'. It checks if two values are different. If JavaScript needs to, it will try to convert the values to the same type before comparing them. This is called 'type coercion'.
1// Comparing numbers2let num1 = 10;3let num2 = 5;4console.log(num1 != num2); // true, because 10 is not equal to 556// Comparing a number and a string with the same value7let num3 = 7;8let str1 = "7";9console.log(num3 != str1); // false, because JavaScript converts "7" to a number, then 7 == 71011// Comparing different strings12let word1 = "hello";13let word2 = "world";14console.log(word1 != word2); // true, because "hello" is not equal to "world"1516// Comparing with null and undefined17let valueA = null;18let valueB = undefined;19console.log(valueA != valueB); // false, because null and undefined are loosely equal
Watch Out for Type Coercion!
The biggest mistake with != is forgetting that JavaScript tries to convert types. For example, 5 != "5" gives false because JavaScript sees both as the number 5 after conversion. This can lead to unexpected results.
Strict Inequality (`!==`) Explained
Strict Inequality (`!==`) Explained
The !== operator means 'strictly not equal'. It checks if two values are different and if their data types are different. It does not perform type coercion. This means the values must be exactly the same type and value to be considered equal. If either the value or the type is different, !== returns true.
1// Comparing numbers2let a = 10;3let b = 5;4console.log(a !== b); // true, because 10 is not equal to 5 (and types are same)56// Comparing a number and a string with the same value7let c = 7;8let d = "7";9console.log(c !== d); // true, because their types are different (number vs string)1011// Comparing same values and types12let e = "apple";13let f = "apple";14console.log(e !== f); // false, because they are strictly equal (same value and same type)1516// Comparing with null and undefined17let valueX = null;18let valueY = undefined;19console.log(valueX !== valueY); // true, because null and undefined are different types
let age = 25;let ageInput = "25";// This might surprise you!if (age != ageInput) {console.log("Age is not equal to ageInput (loose check).");} else {console.log("Age IS equal to ageInput (loose check)!"); // This runs!}
let age = 25;let ageInput = "25";// This is clearer and saferif (age !== ageInput) {console.log("Age is strictly not equal to ageInput."); // This runs!} else {console.log("Age IS strictly equal to ageInput.");}
Choosing Between `!=` and `!==`
Choosing Between `!=` and `!==`
You now know there are two ways to check for inequality. The choice depends on whether you want JavaScript to convert types for you. Most of the time, strict inequality (!==) is the better choice. It helps you avoid unexpected behavior caused by type coercion.
// Use when you don't care about the data type// and are okay with JavaScript converting types.let quantity = 10;let input = "10";// This is false because JavaScript converts "10" to 10if (quantity != input) {console.log("Values are different after type conversion.");} else {console.log("Values are considered the same after type conversion.");}// Example: null and undefined are loosely equalconsole.log(null != undefined); // false
// Use when you need values AND types to be different.// This is generally recommended for safety.let quantity = 10;let input = "10";// This is true because number 10 is not strictly equal to string "10"if (quantity !== input) {console.log("Values or types are different.");} else {console.log("Values and types are strictly the same.");}// Example: null and undefined are strictly not equalconsole.log(null !== undefined); // true
// Use when you don't care about the data type// and are okay with JavaScript converting types.let quantity = 10;let input = "10";// This is false because JavaScript converts "10" to 10if (quantity != input) {console.log("Values are different after type conversion.");} else {console.log("Values are considered the same after type conversion.");}// Example: null and undefined are loosely equalconsole.log(null != undefined); // false
// Use when you need values AND types to be different.// This is generally recommended for safety.let quantity = 10;let input = "10";// This is true because number 10 is not strictly equal to string "10"if (quantity !== input) {console.log("Values or types are different.");} else {console.log("Values and types are strictly the same.");}// Example: null and undefined are strictly not equalconsole.log(null !== undefined); // true
Always Prefer Strict Inequality
As a best practice, always use !== unless you have a very specific reason to use !=. Strict inequality makes your code clearer and less prone to bugs because it doesn't try to guess what you mean by converting types.
Practical Uses in Web Development
Practical Uses in Web Development
Inequality operators are used all the time in real web projects. They help control the flow of your program. You might use them to check user input, validate forms, or make sure certain conditions are not met before performing an action.
Check if a variable is not a specific value
You might want to run code only if a user's role is not 'admin'. This ensures only non-admin users can access certain features.
1let userRole = "editor";23if (userRole !== "admin") {4 console.log("User is not an admin. Showing regular user features.");5}67let statusCode = 404;8if (statusCode !== 200) {9 console.log("Something went wrong! Status code is not 200 (OK).");10}
Ensure a form field is not empty
Before submitting a form, you often need to check if required fields have been filled out. If a field's value is an empty string, it means the user hasn't typed anything.
1let usernameInput = "ChilluCoder"; // Imagine this comes from a form field23if (usernameInput !== "") {4 console.log("Username field is filled. Proceeding...");5} else {6 console.log("Username field cannot be empty!");7}89let passwordInput = "";10if (passwordInput === "") {11 console.log("Password field cannot be empty!");12}
Verify an item is not found in a list
Sometimes you need to add an item to a list only if it's not already there. Or you might want to perform an action if a specific item is missing.
1let shoppingCart = ["milk", "eggs", "bread"];2let newItem = "cheese";34// Check if 'cheese' is NOT in the cart5if (!shoppingCart.includes(newItem)) {6 shoppingCart.push(newItem);7 console.log(`${newItem} added to cart.`);8} else {9 console.log(`${newItem} is already in the cart.`);10}1112console.log("Current cart:", shoppingCart);
Ignoring Strictness Can Lead to Bugs
If you rely on != when you should use !==, your code might behave unpredictably. For example, checking if a user ID 123 (number) is not equal to a database ID '123' (string) with != would incorrectly return false. This could allow wrong data to be processed or actions to be taken.
Inequality Operator Reference
Inequality Operator Reference
| Operator | Description | Type Coercion | Example |
|---|---|---|---|
| `!=` | Loose inequality: checks if values are different. | Yes, attempts to convert types before comparing. | `5 != "5"` is `false` |
| `!==` | Strict inequality: checks if values *or* types are different. | No, does not convert types. | `5 !== "5"` is `true` |
Test Your Knowledge
Test Your Knowledge
What is the result of 10 != "10" in JavaScript?
Which operator checks if values are different AND their types are different?
What is the result of null !== undefined?
Why is !== generally preferred over !=?
Quick Reference
Quick Reference
- 1Inequality Operators — Used to check if two values are not equal.
- 2
!=(Loose Inequality) — Checks if values are different, performing type coercion if needed. - 3
!==(Strict Inequality) — Checks if values or types are different, without type coercion. - 4Type Coercion — JavaScript's automatic conversion of one data type to another during comparison.
- 5Prefer
!==— Always use strict inequality unless you have a specific reason for loose comparison, to avoid bugs. - 6
null != undefinedisfalse— Becausenullandundefinedare loosely considered equal. - 7
null !== undefinedistrue— Becausenullandundefinedhave different types. - 8Comparing Objects/Arrays — Inequality operators check if they are the same object in memory, not if their contents are identical.
- 9Conditional Logic — Inequality operators are crucial for
ifstatements and loops to control program flow. - 10Readability — Using
!==makes your code's intent clearer, as it explicitly requires both value and type to differ.
Equality Operators
Learn about == and === to compare if values are the same.
Conditional Statements
Understand how if/else statements use comparison results to make decisions.
Logical Operators
Explore && (AND), || (OR), and ! (NOT) to combine or negate conditions.
Data Types in JS
Deepen your knowledge of JavaScript's data types (numbers, strings, booleans, etc.) and how they behave.
Congratulations!
You've mastered JavaScript's inequality operators! You now understand the difference between loose (!=) and strict (!==) comparisons and why !== is the safer choice for robust code. Keep practicing to build strong logical foundations for your programs.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.