Last active
January 25, 2024 22:01
-
-
Save joakim/dd598d9c6b783cd7641100bc70215e68 to your computer and use it in GitHub Desktop.
The concept of nothing in JavaScript (Crockford's idea of a better undefined)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
nothing = new Proxy(Object.freeze(Object.create(null)), { | |
get(target, property) { | |
if (property === Symbol.toPrimitive) return () => undefined | |
return nothing | |
}, | |
set() { | |
return nothing | |
} | |
}) | |
nothing.foo === nothing // true | |
nothing.foo.bar.baz[42].qux // nothing (forever) | |
nothing.foo = 42 // 42 (would ideally return nothing) | |
nothing.foo // nothing | |
typeof nothing // "object" | |
Reflect.getPrototypeOf(nothing) // null | |
// coerced to the primitive value undefined | |
nothing + nothing // NaN | |
nothing + true // NaN | |
nothing + false // NaN | |
nothing + 42 // NaN | |
"hello, " + nothing // "hello, undefined" | |
nothing + {} // "undefined[object Object]" | |
nothing + [] // "undefined" | |
nothing + 0n // TypeError: can't convert BigInt to number | |
nothing + Symbol() // TypeError: can't convert symbol to number | |
nothing / nothing // *implodes* (no, it's NaN) | |
// it is unfortunately truthy because an object can't be falsy | |
Boolean(nothing) // true |
I think that NaN should also be unified, so that 1/ 0 is nothing, and nothing + 1 is nothing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Crockford's idea of "null" as an immutable object that only ever returns itself:
https://www.youtube.com/watch?v=NPB34lDZj3E#t=12m23s
Of course, this implementation means nothing(…) if we can't override
undefined
itself.But it's nice to see what we could've had! Or is it 🤔