Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the use of Object.is() method in JavaScript?
The Object.is() method determines whether two values are strictly equal, providing more precise comparison than the regular equality operators.
Syntax
Object.is(value1, value2)
Parameters
- value1: The first value to compare
- value2: The second value to compare
Return Value
Returns true if both values are the same, false otherwise.
How Object.is() Determines Equality
Two values are considered the same when they meet these criteria:
- Both are
undefinedor both arenull - Both are
trueor both arefalse - Both are strings with same length, characters, and order
- Both are numbers with same value and same sign (including polarity of zero)
- Both are
NaN - Both refer to the same object
Example: Basic Comparisons
<html>
<body>
<script>
// String comparison
console.log(Object.is("tutorialspoint", "tutorialspoint"));
// Number comparison with polarity
console.log(Object.is(-0, +0));
// Unequal strings
console.log(Object.is("tutorialspoint!", "tutorialspoint"));
// NaN comparison
console.log(Object.is(NaN, NaN));
</script>
</body>
</html>
true false false true
Object.is() vs == vs ===
The key differences between comparison methods:
| Comparison | == (Loose) | === (Strict) | Object.is() |
|---|---|---|---|
+0 vs -0 |
true | true | false |
NaN vs NaN |
false | false | true |
| Type coercion | Yes | No | No |
Example: Special Cases
<html>
<body>
<script>
// Demonstrating the differences
console.log("=== comparison:");
console.log(+0 === -0); // true
console.log(NaN === NaN); // false
console.log("Object.is() comparison:");
console.log(Object.is(+0, -0)); // false
console.log(Object.is(NaN, NaN)); // true
// Object comparison
let obj1 = {a: 1};
let obj2 = {a: 1};
console.log(Object.is(obj1, obj2)); // false - different objects
console.log(Object.is(obj1, obj1)); // true - same reference
</script>
</body>
</html>
=== comparison: true false Object.is() comparison: false true false true
Common Use Cases
- Checking for
NaNvalues more reliably - Distinguishing between positive and negative zero
- Implementing custom equality functions
- Polyfill for environments lacking
Object.is()
Conclusion
Object.is() provides the most precise equality comparison in JavaScript, especially useful for edge cases with NaN and signed zeros. Use it when you need strict value comparison without type coercion.
Advertisements
