Search code examples
javascriptloopsobjectfor-in-loop

Trying to understand For In Loops


something is bugging me at the moment about For In Loops. I understand how to use them but what I can't seem to get my head around is.. Well, in this example:

const tree = {
  name: 'Oak',
  ageInYears: 358,
  hasAcorns: true,
}

for (const key in tree) {
  console.log(tree[key]);
}

What I don't understand is how is that showing the values of the keys, because my understanding is that the key variable is looping through the keys of the object, not the values. So, why would logging simply 'key' return the keys, but logging 'tree[key]' log the values.. I'm so confused about it and it's bugging me not being able to understand what is really happening here.

Hopefully this question makes sense.

Thanks.


Solution

  • You have 2 ways to access an object property: static & dynamic. In for..in loop you use the dynamic one.

    You use the static one when you know the property name in the time of writing your property access. You use the dynamic when you don't know the property name in the time of writing your property access, that happens in for..in for example

    const tree = {
       name: 'Oak',
       ageInYears: 358,
       hasAcorns: true,
    };
    
    // access property statically:
    console.log('static property access: ', tree.name);
    
    // access property dynamically:
    const propertyName = 'name';
    console.log('dynamic property access: ', tree[propertyName]);