1

I am trying to implement the algorithm described in ES262, The Abstract Equality Comparison Algorithm. It states:

  1. If Type(x) is the same as Type(y), then

    a. If Type(x) is Undefined, return true.

    b. If Type(x) is Null, return true.

So when we perform the comparison:

console.log(null == {})

it should evaluate to true, because null and {} have the same type. Do I understand it correctly?

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
neoexpert
  • 465
  • 1
  • 10
  • 20
  • 1
    in javascript the expression (typeof null === typeof {}) evaluates to true – neoexpert Jan 03 '22 at 09:01
  • 1
    `typeof null` being `object` is actually a bug and not an intended feature. No one fixed the bug because of backwards compatibility issues – apokryfos Jan 03 '22 at 09:02
  • I just checked and you are correct – mplungjan Jan 03 '22 at 09:02
  • 1
    https://2ality.com/2013/10/typeof-null.html#:~:text=In%20JavaScript%2C%20typeof%20null%20is,it%20would%20break%20existing%20code. – mplungjan Jan 03 '22 at 09:02
  • 1
    Also by this logic `null == { foo: 'bar' }` should also be true – apokryfos Jan 03 '22 at 09:06
  • 7
    `Type()` in the spec is **not the same as `typeof`.** `null` **does** have its own *internal type*, Null, just [`typeof` returns `"object"` for it, too.](https://262.ecma-international.org/5.1/#sec-11.4.3) – FZs Jan 03 '22 at 09:08
  • Just because 2 instances have the same type, doesn't mean they are the same instances. – gre_gor Jan 03 '22 at 09:20
  • 1
    @FZs I believe that should be an answer to this question – Jonas Wilms Jan 03 '22 at 10:22
  • In [the specs](https://262.ecma-international.org/6.0/) If you look at section 6 where it describes the types used in JavaScript you'll notice that there is a `Null` type (6.1.2) and an `Object` type (6.1.7). – Salman A Jan 03 '22 at 10:31

1 Answers1

2

it should evaluate to true because null and {} have the same type and x is null,

This is your mistake.

The types are different.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I think my mistake was to assume that typeof operator behaves in the same way like the Type() operator used in the documentation. – neoexpert Jan 03 '22 at 11:41