top | item 46072029

(no title)

h1fra | 3 months ago

so like assert(process.env.MY_ENV_VAR) but in a less readable oneliner?

discuss

order

t-writescode|3 months ago

Since JS doesn’t have if statements return values, null chaining is a great way to keep both const variables and have some level of decidability.

Null chaining is also a common pattern across most languages and is generally seen as readable

MobiusHorizons|3 months ago

I get why we prefer final in languages with a need for thread safety, but I have never understood why people prefer const in typescript. I have seen people bend over backwards to avoid a `let` even if it results in higher complexity code. It just doesn’t seem to solve a problem I’ve ever actually encountered in typescript code.

kbolino|3 months ago

Assuming assert existed, it would almost certainly be judging its value for being falsy, while the ?? operator judges its LHS for being nullish, which is a narrower category. For strings, this affects whether the empty string is acceptable or not.

xscott|3 months ago

> Assuming assert existed

It's a function you could write for yourself and give it whatever semantics you feel is best. No changes to the language required for this one.

fainpul|3 months ago

  console.assert(maybeNull != null, 'variable not set')

ameliaquining|3 months ago

There isn't a built-in assert function that behaves that way; you would need to either write it or import it.

xscott|3 months ago

I'm not a web dev. Are people really that opposed to writing a function which would solve problems in their project? It's two lines long...

jackblemming|3 months ago

That doesn’t assign it to the shorthand local variable.

zdragnar|3 months ago

It could return the given value if it doesn't throw, though, which would make using it with assignment trivial.