denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.6k stars 2.54k forks source link

[Example] const is equal to multiple numbers #286

Open AlexXanderGrib opened 1 year ago

AlexXanderGrib commented 1 year ago

Example

const a = new Proxy({ i: 1 }, { 
  get: (target) => () => target.i++,
})

console.log(a == 1, a == 2, a == 3);

Explaination

  1. Every time when comparing, property [Symbol.toPrimitive] is accessed
  2. Proxy returns a function, that is called
  3. So value is compared with result of the function
const a = new Proxy({ i: 1 }, {
  get(target, property) {
    console.trace("[Proxy] get() called with", { target, property });

    return function inner() {
      console.trace("[Proxy] inner() called");

      return target.i++;
    }
  }
})

console.log(a == 1, a == 2, a == 3);

Log

[Proxy] get() called with
{
  target: { i: 1 },
  property: Symbol(Symbol.toPrimitve)
}
[Proxy] inner() called
...

Basically, object is equal to

const a = {
  i: 1,
  [Symbol.toPrimitive]() {
    return this.i++;
  }
}