Skip to content

Instantly share code, notes, and snippets.

@Sheraff
Forked from joakim/nothing.js
Created February 2, 2021 20:42
Show Gist options
  • Save Sheraff/237ac69d2e653e18f6d36b71d7bf8252 to your computer and use it in GitHub Desktop.
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)
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