0

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);
In this experiment i just added a console.log(hello); and now de-structuring works fine.

So there is two question

  1. In example #1, why it's saying that hello is not declared, as it is declared right before de-structuring ?
  2. In example #2, why it's working just adding console.log(hello) before de-structuring ?
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44

0 Answers0