0

I want to get deep understanding of the for...of loops and destructuring assignment in JS. The following code throw an error on line 3: "ReferenceError: y is not defined", but "y" is defined just before the for loop statement. What's the problem?

let arr = [ ];
let y = 8;
for (let { x = 2, y } of [{ x: 1 }, 2, { y }]) {  
    arr.push(x, y);
}
console.log(arr);
v1r00z
  • 103
  • 5

1 Answers1

2

It seems that y is in a temporal dead zone in the for block.

Not using y in the object initialisation solves the problem:

let arr = [];
let z = 8;
for (let { x = 2, y } of [{ x: 1 }, 2, { y: z }]) {  
  arr.push(x, y);
}
console.log(arr);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • This is weird. It's [an environment explicitly created for evaluating only this expression](http://www.ecma-international.org/ecma-262/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind), what would it be used for? – Bergi Jan 08 '19 at 09:25
  • It seems that they separate the head from the body, and each has a TDZ of each own. – Ori Drori Jan 08 '19 at 19:14