I have tried the following JavaScript code:
> var {a} = undefined;
Thrown:
TypeError: Cannot destructure property `a` of 'undefined' or 'null'.
> var {a} = false;
undefined
Essentially, can someone explain this error to me? Why does it occur, and how does {a} get set as undefined in the second line?
In the first example you try to access field a of undefined, which leads to error. You can try to access undefined fields manually:
console.log(undefined.a);
It will lead to:
Uncaught TypeError: Cannot read property 'a' of undefined
In the second example you access a field of false, but false doesn't have a field, that's why it is undefined. You can test it manually to:
console.log(false.a);
// undefined
If you want to avoid undefined values after destructuring you can assign a default value:
let { a = "default value" } = false;
console.log(a);
// default value