I've begun planning a JS library that I hope that would be published on NPM. As a self-taught programmer, I'm continually learning that observing other peoples' code is incredibly important. As I take notes for similar JS libraries to inspire me, I stumbled on this interesting line of Javascript.
debug = typeof value === 'boolean' ? value : debug
Here's the function scope for full context:
Object.defineProperty(ScrollReveal, 'debug', {
get: () => debug || false,
set: value => (debug = typeof value === 'boolean' ? value : debug)
})
I use ternary statements constantly in my freelance web development, but the beginning part of the line is very interesting, as I've never seen this type of assignment/destructing in a ternary before. I didn't know that it was a thing, and it's brilliant.
Left-to-right, the setter is returning (like all ternaries do) a value, but what makes this different is the debug =
part, which is assigning typeof value
to the lexical variable: debug
. So, when using this setter function, if the parameter isn't a boolean, it makes a small referential loop to debug
, which is whatever type the parameter is.
I see this being useful for more concisely skipping type clauses in functions, but for when approaching an interface in a negating direction (instead of adding allowed types like string | boolean
). If you want to make a type by remove types from any
(in JS instead of Typescript world), perhaps this is a nice clean way of doing that.
The beauty of Javascript (or just any programming): You'll always learn more.
Top comments (0)