nick zoum
nick zoum

Reputation: 7295

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).

Upvotes: 9

Views: 1593

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

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

Upvotes: 5

Related Questions