JavaScript Basics: Object.is

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@ghasemkiani·
0.000 HBD
JavaScript Basics: Object.is
You may have heard of the book [_JavaScript: The Good Parts_](http://shop.oreilly.com/product/9780596517748.do) (Yahoo Press, December 2008) by [Douglas Crockford](https://www.crockford.com/). The name, obviously, implies that JavaScript has bad parts, too. The equality operator `==` is one aspect of JavaScript that is considered a bad part. Crockford writes in this book:

> “JavaScript has two sets of equality operators: `===` and `!==`, and their evil twins `==` and `!=`. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then `===` produces `true` and `!==` produces `false`. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable.”

So the problem with the `==` operator is that it performs unexpected and complicated type conversions. For this reason, it is recommended that you always use `===` and never use `==`.

`Object.is` is yet a new addition to JavaScript that tests for equality. It behaves like the `===` operator, with two exceptions: Contrary to the `===` operator, it treats `+0` and `-0` as not equal, and it treats `NaN` and `Number.NaN` as equal. Otherwise, it behaves like `===`. In other words, it returns true if both operands are `undefined`, both are `null`, both are `true` or `false`, both are strings with the same length and the same characters, both are the same object, or both are numbers with the same value.

Here are a few examples:

```
	Object.is("hi", "hi"); // true
	Object.is(undefined, null); // false
	Object.is("", false); // false
	Object.is(+0, -0); // false
	+0 === -0; // true
	Object.is(NaN, Number.NaN); // true
	Number.NaN === NaN; // false
```

It is evident that `Object.is` is the best way to test for equality in JavaScript.

---

## Related Posts

* [JavaScript Basics: Object.create](https://steemit.com/javascript/@ghasemkiani/javascript-basics-01)
* [JavaScript Basics: Object.assign](https://steemit.com/javascript/@ghasemkiani/javascript-basics-02)
* [JavaScript Basics: Object.getPrototypeOf and Object.setPrototypeOf](https://steemit.com/javascript/@ghasemkiani/javascript-basics-03)
* [JavaScript Basics: Object.keys, Object.values, and Object.entries](https://steemit.com/javascript/@ghasemkiani/javascript-basics-04)
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,