Skip to content

Instantly share code, notes, and snippets.

@joakim
Last active January 25, 2024 22:01
Show Gist options
  • Save joakim/dd598d9c6b783cd7641100bc70215e68 to your computer and use it in GitHub Desktop.
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)
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
@joakim
Copy link
Author

joakim commented Jan 13, 2021

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 🤔

@joakim
Copy link
Author

joakim commented Jan 13, 2021

The Proxy and the getter degrades performance, but that shouldn't matter much when it's at the bottom. I mean, it's nothing.

Oh, and I think nothing is a good word for a unit type. Julia seems to agree.

@douglascrockford
Copy link

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