Using Object.is to compare two values
JavaScript has a complex relationship with equality. It is common knowledge that using ===
is preferable to ==
because it gives more predictable results, and in most cases ===
behaves as expected. Unfortunately, due to quirks in the JavaScript type system, there are some frustrating edge cases. In this recipe, we'll see how to use Object.is
to get expected results for comparisons.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
06-03-compare-with-object-is
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
with amain
function that makes a few illustrative comparisons:
// main.js export function main() { const obj1 = {}; const obj2 = {}; console.log('obj1 === obj2', obj1 =...