avatargravity well (Rob Tomlin)

Summary

The provided content discusses JavaScript's Object.is() method, emphasizing its use for comparing primitives without type coercion, in contrast to the == and === operators.

Abstract

The article "JavaScript’s Object.is" is a brief follow-up to a previous piece on comparing objects in JavaScript. It highlights the Object.is() method, which compares primitives without applying type coercion, unlike the == operator. The method is recommended for precise comparisons, as it checks both value and type, similar to the === operator but with nuanced differences, such as handling NaN and -0 and +0. The author stresses the importance of choosing the correct comparison operator, noting that Object.is() is particularly useful for comparing primitive data types and not just reference values. The article concludes by advising readers to be mindful of the type of comparison operator used in JavaScript.

Opinions

  • The author believes that understanding the nuances between ==, ===, and Object.is() is crucial for JavaScript developers.
  • The importance of type coercion is emphasized when comparing values in JavaScript.
  • The author acknowledges the contribution of a reader's comment in prompting the discussion on Object.is().
  • The article suggests that Object.is() should be considered when precise comparisons are necessary, especially with primitives.

JavaScript’s Object.is

On Primitives and The Importance of ===

Photo by Bankim Desai on Unsplash

This is a very short article as an add-on to Comparing Objects In JavaScript.

At the tail end of that article I mentioned Object.is() and it’s role in comparing Objects.

Thanks to a comment by a reader of that article, I thought I’d mention Object.is() and how it works with primitive data types and not just reference values.

What about Comparing Primitives

One of the statements on the MDN about Object.is(), is,

This is not the same as being equal according to the == operator. The == operator applies various coercions to both sides (if they are not the same Type) before testing for equality (resulting in such behavior as "" == false being true), but Object.is doesn't coerce either value.

That last part about type coercion is important, as well as the difference between the == and === comparison operators.

Example

Object.is(), == and ===

Conclusion

Make sure you are using the right type of comparison operator.

Remember, the main difference between == and === operators is that == compares variables but performs type coercion. But === doesn’t do that. It checks not only the values but also types of two variables.

Thanks for taking the time to read this!

JavaScript
Type Coercion
Web Development
Programming
Coding
Recommended from ReadMedium