Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override the truthy coercion of a JavaScript Object?

The string coercion can be overwritten using the toString function.

The number coercion can be overwritten using the valueOf function.

The boolean coercion can be also overwritten using the valueOf function.

var foo = {
  toString: function() {
    console.log("To String");
    return "bar";
  },
  valueOf: function() {
    console.log("Value Of");
    return 5;
  }
};

console.log(`${foo}`);
console.log(+foo);
console.log(foo == true);
console.log(!!foo);

I haven't been able to find a function that gets called for when an object needs to get converted to a truthy. Since x == true and !!x have different behaviors, then I am guessing that there is no function that changes that. I instead tried extending types whose truthy is false but the only value that gets accepted by Object.create is null which is almost identical to an object literal (has none of the Object.prototype properties).

like image 366
nick zoum Avatar asked Mar 08 '19 19:03

nick zoum


1 Answers

foo == true actually converts foo to a number, that's why valueOf works, but it's misleading.
You can try {} == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that).

!foo however calls ToBoolean, which explicitly always returns true for an object. There is no way to override that behavior.

enter image description here

like image 75
Felix Kling Avatar answered Oct 24 '22 05:10

Felix Kling