What is Strict Equality in JavaScript: Explanation and Examples
strict equality is checked using the === operator, which compares both the value and the type of two variables. It returns true only if both are exactly the same without any type conversion.How It Works
Strict equality in JavaScript means checking if two things are exactly the same in both value and type. Imagine you have two boxes: one labeled "number" with the value 5, and another labeled "string" with the value "5". Even though the numbers look similar, strict equality says these boxes are different because their labels (types) don't match.
Unlike loose equality (==), which tries to convert types to compare values, strict equality (===) does no conversion. It’s like checking ID cards carefully before saying two people are the same. This helps avoid unexpected results and bugs in your code.
Example
This example shows how strict equality compares both value and type, returning true only when both match exactly.
console.log(5 === 5); // true because both are number 5 console.log(5 === '5'); // false because types differ (number vs string) console.log(true === 1); // false because boolean vs number console.log(null === null); // true because both are null console.log(undefined === undefined); // true console.log(NaN === NaN); // false because NaN is not equal to itself
When to Use
Use strict equality when you want to be sure that two values are exactly the same without any guessing or type conversion. This is important in real-world coding to avoid bugs caused by unexpected type changes.
For example, when checking user input, comparing IDs, or validating data, strict equality ensures your program behaves predictably. It’s a safer choice than loose equality, especially in large or complex projects.
Key Points
- Strict equality uses
===and compares both value and type. - It does no type conversion, unlike loose equality (
==). - It helps avoid bugs by ensuring exact matches.
- Use it for safe and predictable comparisons.
- Special cases:
NaN === NaNisfalse, so useNumber.isNaN()to check forNaN.