Search code examples
javascriptvalidationdestructuring

Is the {foo = foo} validation trick in destructuring a safe pattern to adopt?


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.


Solution

  • 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.