0

Example of the behaviour.

When testing for equality in object literals, {} === {} returns false (so does [] === []). However, if you write a function to perform the same test and pass an object literal as a parameter, the comparison returns true.

function foo(value) {
    return value === value
} 

foo({}) //Returns true! 

Is anyone able to explain this behaviour?

1 Answers1

2

The simple answer to this is because the expression {} === {} is taking two object literals, while in the function foo you are taking a singular value and comparing it against itself. In fact, foo will always return true (see edit).

A better way to look at this would be:

const a = {}
const b = {}

console.log(a === b) // false, symmetric to {} === {}
console.log(a === a) // true, symmetric to (val) => val === val

edit: Ryan did point out that when passed NaN, it would short-circuit to false as defined in 11.9.3c.

woat
  • 431
  • 3
  • 8