I tried to de-structure a object in javascript as following
Example #1
var a, b
var hello = {
a: 1,
b: 3
}
({a, b} = hello);
console.log(a);
If you hit Run code snippet you will encounter
{ "message": "Uncaught TypeError: Cannot destructure property 'a' of 'hello' as it is undefined.", "filename": "https://stacksnippets.net/js", "lineno": 18, "colno": 3 }
Example #2
var a, b
var hello = {
a: 1,
b: 3
}
console.log(hello);
({a, b} = hello);
console.log(a);
console.log(hello);
and now de-structuring works fine.
So there is two question
- In example #1, why it's saying that
hello
is not declared, as it is declared right before de-structuring ? - In example #2, why it's working just adding
console.log(hello)
before de-structuring ?