Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does property access in a for-of loop do, like `for (a.b of c)`? [duplicate]

I encountered this obscure syntax:

const a = {}
const c = [1,2,3]

for (a.b of c) {}

assert(a.b === 3)

How does it work?

like image 623
golopot Avatar asked Sep 11 '19 07:09

golopot


Video Answer


2 Answers

It just puts each iteration value into that property value of the existing object.

const a = {}
const c = [1,2,3]

for (a.b of c) {
  console.log(a.b);
}
console.log(a.b);
console.log(a);

It can be any existing reference:

const a = {
  foo: [
    {
      nested: 'nestedVal'
    }
  ]
}
const c = [1,2,3]

for (a.foo[0].nested of c) {
  console.log(a.foo[0].nested);
}
console.log(a.foo[0].nested);
console.log(a);

Including a standalone variable:

let a;
const c = [1,2,3]

for (a of c) {
  console.log(a);
}
console.log('a is:', a);

Or you can create a binding for each iteration with const or let, eg const item of c, as you probably already know.

like image 181
CertainPerformance Avatar answered Oct 27 '22 04:10

CertainPerformance


You can easily have a look at by logging the a variable.

By assigning a.b you hold the value of iteration at b property of a.

Please have a look at the following snippet:

const a = {}
console.log(a);

const c = [1,2,3]

for (a.b of c) {
  console.log(a);
}

Hope this helps.

like image 41
Harun Yilmaz Avatar answered Oct 27 '22 04:10

Harun Yilmaz