top | item 46071831

(no title)

ryanpetrich | 3 months ago

Should throw expressions (https://github.com/tc39/proposal-throw-expressions) ever make it into the JavaScript standard, the example could be simplified to:

  const env_var = process.env.MY_ENV_VAR ?? throw new Error("MY_ENV_VAR is not set");

discuss

order

h1fra|3 months ago

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

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

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.

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.

jackblemming|3 months ago

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