-
-
Save Sheraff/237ac69d2e653e18f6d36b71d7bf8252 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 hidden or 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
const nothing = new Proxy(Object.freeze(Object.create(null)), Object.create(null, { | |
get: { value(target, property) { | |
return property === Symbol.toPrimitive ? () => null : nothing } | |
} | |
})) | |
nothing.foo === nothing // true | |
nothing.foo.bar.baz[42].qux // nothing forever | |
typeof nothing === "object" // true | |
Reflect.getPrototypeOf(nothing) // null | |
nothing.foo = 42 // 42 | |
nothing.foo // nothing | |
// coerced to the primitive value null (not ideal, but better than undefined) | |
nothing + true // 1 | |
nothing + false // 0 | |
nothing + 42 // 42 | |
"hello, " + nothing // "hello, null" | |
nothing + {} // "null[object Object]" | |
nothing + [] // "null" | |
nothing + 0n // TypeError: can't convert BigInt to number | |
nothing + Symbol() // TypeError: can't convert symbol to number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment