How can you cause a javascript Object to be treated as falsy?

109 Views Asked by At

The use case I'm considering is creating a hopelessly egocentric Null for coalescing.

This code works but requires an explicit check against the Null in question:

const Null = new Proxy({}, {get: () => Null});

let data = Null;

console.log(data.a.b.c.d !== Null ? "Has value" : "Is Null");

I'd like to be able to leave out the explicit check and simply do

console.log(data.a.b.c.d ? "Has value" : "Is Null");

but that doesn't work because my Null is an object, and as such is treated as truthy.

The spec seems to indicate that this isn't possible, but javascript is such a weird ecosystem that I'm hoping someone will be able to come up with a possible solution.

(Also please don't debate the merits of this kind of Null, I know it's a potentially contentious issue and I'm purely interested in if it CAN be done, not whether it SHOULD be done.)

1

There are 1 best solutions below

9
On

No, you cannot. An object reference is never "falsy". You can add valueOf() and toString() methods that return false values when they're invoked, but if all that's tested is a reference that won't do any good.