1

I've read this trick in an answer here, that it's possible to validate for the presence of foo property like this:

const {foo = foo} = bar

It throws Uncaught ReferenceError: Cannot access 'foo' before initialization when foo is undefined.

Is this a well-defined behaviour in JS? Would this work reliably for all recent JavaScript versions and environments (browser, node) and likely future ones?

I am trying to see if it could make sense to start using this as a convenient shorthand validation if I don't care about having a more specific error message. Thanks.

blutogin
  • 13
  • 5

1 Answers1

2

Is this a well-defined behaviour in JS?

Yes. It relies on the temporal dead zone of const and let variables. It might not work if these are transpiled to var though.

I am trying to see if it could make sense to start using this as a convenient shorthand validation

No, please don't. This is really obscure and confusing code, and every linter will complain about use-before-define. Even if you don't care about a specific error message, at least use

const {foo = error()} = bar;

with a throwing error function to make the intention clear.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks! Agree that it's confusing code, and IDE / lint will not like it either... so better to go with the error function alternative. I wanted to avoid importing that everywhere and trying to find a JS built-in feature to do this. – blutogin Aug 23 '20 at 13:08