v1r00z
v1r00z

Reputation: 103

Destructuring assignment in for...of loop and execution context in Javascript

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);

Upvotes: 0

Views: 152

Answers (1)

Ori Drori
Ori Drori

Reputation: 192222

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);

Upvotes: 2

Related Questions