Question
JavaScript == vs ===: Which Equality Operator Should You Use?
Question
I'm using JSLint on some JavaScript code, and it suggests replacing == with === in comparisons such as this:
if (idSele_UNVEHtype.value.length == 0) {
// ...
}
Should === be preferred over == in JavaScript comparisons?
I want to understand:
- Is there any performance benefit to using
===instead of==? - Why do linters usually recommend
===? - If no type conversion happens, is
===still better than==?
Short Answer
By the end of this page, you'll understand the difference between JavaScript's loose equality operator (==) and strict equality operator (===). You'll learn how type coercion affects comparisons, why === is usually the safer default, whether performance matters, and how real codebases handle equality checks.
Concept
In JavaScript, both == and === compare two values, but they do it differently.
==checks for equality after possible type conversion.===checks for equality without type conversion.
That difference is the main reason developers strongly prefer ===.
Loose equality: ==
When you use ==, JavaScript may try to convert one or both values to a common type before comparing them.
Examples:
0 == "0" // true
false == 0 // true
"" == 0 // true
null == undefined // true
These results can be surprising, especially for beginners.
Strict equality: ===
When you use ===, both the value and the type must match.
Examples:
0 === "0" // false
false === 0 // false
"" === 0 // false
null === undefined // false
This makes code easier to read, predict, and debug.
Why this matters
In real programs, values often come from:
- form inputs
- APIs
- query strings
- local storage
- JSON data
- user input
These sources may return strings, numbers, booleans, or null values in different situations. If you use ==, JavaScript may silently convert types and produce a result you did not expect.
Using === helps avoid bugs caused by implicit coercion.
What about performance?
In practice, performance is not the reason to choose ===.
- Modern JavaScript engines optimize both operators very well.
- The difference is usually tiny and irrelevant in normal application code.
- Correctness and clarity matter much more than micro-optimizations here.
If no type conversion would happen anyway, then == and === may behave the same for that comparison. But === is still preferred because it communicates intent clearly: compare exactly, without coercion.
Mental Model
Think of == and === like two different security checks.
==is a guard who says, "You don't look exactly right, but I'll convert your badge and see if it matches."===is a guard who says, "Your badge and identity must already match exactly."
With ==, JavaScript may "adjust" values before deciding.
With ===, JavaScript checks them as they are.
That is why === is easier to trust: no hidden conversion step happens first.
Syntax and Examples
The basic syntax looks the same, but the behavior differs.
value1 == value2 // loose equality
value1 === value2 // strict equality
Example 1: Number and string
console.log(5 == "5"); // true
console.log(5 === "5"); // false
Explanation:
==converts the string"5"to the number5===does not convert types, so number and string are not equal
Example 2: Form input values
HTML form input values are usually strings.
const age = "18";
console.log(age == 18); // true
console.log(age === 18); // false
If you actually want a number comparison, convert the value first:
const age = Number("18");
console.log(age === 18); // true
Example 3: Checking string length
Your original example is a good case for ===:
if (idSele_UNVEHtype.value.length === 0) {
console.log("The input is empty");
}
Why?
lengthis a number0is a number- no type conversion is needed
===makes that explicit
Example 4: One intentional exception
A common exception is checking for both null and undefined together:
if (value == null) {
console.log("value is null or undefined");
}
This works because:
null == undefined // true
Some developers intentionally use this pattern. Outside of special cases like this, === is usually the best default.
Step by Step Execution
Consider this code:
const inputValue = "0";
console.log(inputValue == 0);
console.log(inputValue === 0);
Step 1: Evaluate inputValue == 0
Left side:
"0"
Right side:
0
The types are different:
- left is a string
- right is a number
Because == allows coercion, JavaScript converts the string "0" to the number 0.
Now it compares:
0 == 0
Result:
true
Step 2: Evaluate inputValue === 0
Left side:
"0" // string
Right side:
0 // number
Because === does not coerce types, JavaScript compares them directly.
- string is not number
- types differ
Result:
false
Another trace
const text = "";
console.log(text == 0); // true
console.log(text === 0); // false
Why is text == 0 true?
With ==, JavaScript converts "" to 0, then compares 0 == 0.
That kind of behavior is exactly why strict equality is safer.
Real World Use Cases
Form validation
Form fields usually return strings.
const quantity = input.value;
if (Number(quantity) === 0) {
console.log("Quantity cannot be zero");
}
API response handling
APIs may return numeric-looking values as strings.
if (response.status === 200) {
console.log("Success");
}
If the API returns "200" instead, you should convert it deliberately instead of relying on ==.
Filtering data
const users = [
{ active: true },
{ active: false }
];
const activeUsers = users.filter(user => user.active === true);
Configuration checks
if (config.environment === "production") {
enableCaching();
}
Empty value checks
if (username.length === 0) {
console.log("Username is required");
}
This is predictable because both sides are numbers.
Real Codebase Usage
In real codebases, === is the default choice because it reduces ambiguity.
Common patterns
Guard clauses
function greet(name) {
if (name === "") {
return "Name is required";
}
return `Hello, ${name}`;
}
Validation before processing
function setCount(count) {
if (typeof count !== "number") {
throw new Error("count must be a number");
}
if (count === 0) {
return "Nothing to process";
}
}
Explicit conversion before comparison
const page = Number(query.page);
if (page === 1) {
console.log("Show first page");
}
Checking booleans directly
if (isAdmin === true) {
grantAccess();
}
Often this is simplified to:
if (isAdmin) {
grantAccess();
}
Intentional == null
One common deliberate use of loose equality is:
if (value == null) {
// handles both null and undefined
}
This appears in production code because it is short and intentional. Linters may allow it as a special case depending on configuration.
Common Mistakes
Mistake 1: Assuming == compares values only
console.log(false == 0); // true
Why it happens:
falseis coerced to0
How to avoid it:
- use
=== - convert types yourself before comparing
Mistake 2: Comparing form input directly to numbers
Broken example:
const age = document.querySelector("#age").value;
if (age === 18) {
console.log("Adult");
}
This fails because age is a string.
Better:
const age = Number(document.querySelector("#age").value);
if (age === 18) {
console.log("Adult");
}
Mistake 3: Using == for empty checks without understanding coercion
Broken example:
if (value == 0) {
console.log("Zero");
}
This may also match:
"0"false""
Better:
if (value === 0) {
console.log("Zero");
}
Mistake 4: Confusing null and undefined
console.log(null == undefined); // true
console.log(null === undefined); // false
Use the one that matches your intent:
=== nullif you want onlynull=== undefinedif you want onlyundefined== nullif you intentionally want either one
Mistake 5: Using strict equality but forgetting type conversion
const price = "25";
console.log(price === 25); // false
Strict equality is correct here, but you still need the right type:
const price = Number("25");
console.log(price === 25); // true
Comparisons
| Operator | Name | Type conversion? | Example | Result |
|---|---|---|---|---|
== | Loose equality | Yes, if needed | 5 == "5" | true |
=== | Strict equality | No | 5 === "5" | false |
!= | Loose inequality | Yes, if needed | 5 != "5" | false |
!== | Strict inequality | No | 5 !== "5" | true |
== vs ===
| Topic | == | === |
|---|---|---|
| Readability | Less clear | More clear |
| Predictability | Lower | Higher |
| Implicit coercion | Yes | No |
| Recommended default | Usually no | Usually yes |
| Common safe use case | value == null | Most comparisons |
Which should you choose?
- Use
===by default - Use
!==by default for inequality - Use
==only when you intentionally want coercion and understand the result
Cheat Sheet
// Preferred default
if (a === b) {}
if (a !== b) {}
// Loose equality allows coercion
5 == "5" // true
false == 0 // true
"" == 0 // true
null == undefined // true
// Strict equality does not coerce
5 === "5" // false
false === 0 // false
"" === 0 // false
null === undefined // false
Rules of thumb
- Prefer
===and!== - Convert values explicitly before comparing
- Be careful with form values because they are usually strings
- Do not choose
==for performance reasons - A common intentional exception is:
if (value == null) {
// null or undefined
}
Good examples
if (count === 0) {}
if (name === "") {}
if (isReady === true) {}
if (status !== "success") {}
Better with explicit conversion
if (Number(input.value) === 10) {}
Avoid relying on coercion
if (input.value == 10) {}
FAQ
Is === faster than == in JavaScript?
Usually, the performance difference is negligible. Choose === for correctness and clarity, not speed.
Why do linters recommend ===?
Because it avoids unexpected type coercion and makes comparisons easier to reason about.
Should I always use ===?
Almost always, yes. One common exception is value == null when you intentionally want to match both null and undefined.
What is type coercion in JavaScript?
Type coercion is when JavaScript automatically converts a value from one type to another, such as turning "5" into 5 during a == comparison.
Why does "0" == 0 return true?
Because == converts the string "0" to the number 0 before comparing.
Why does "0" === 0 return false?
Because === compares both value and type, and a string is not the same type as a number.
Is == ever useful?
Yes, but only in specific cases where coercion is intentional and understood, such as value == null.
What should I use for checking empty string length?
Use strict equality:
if (text.length === 0) {
// empty
}
Mini Project
Description
Build a small input-checking script that compares user-provided values safely. This project demonstrates why explicit conversion plus strict equality is more reliable than loose equality when handling form-like input.
Goal
Create a script that validates a few string inputs and compares them correctly using ===.
Requirements
- Create variables that simulate user input as strings.
- Convert numeric input to a number before comparing it.
- Use
===for all main comparisons. - Show at least one example where
==would give a misleading result. - Print clear messages to the console for each check.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.