1

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.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
James
  • 107
  • 1
  • 8
  • 4
    Because `tree[key]` is how you access the value associated with the given key in an object. – ndc85430 Jun 17 '23 at 10:44
  • 1
    What would you expect `tree['name']` to return? – Hans Kesting Jun 17 '23 at 10:51
  • 1
    @HansKesting I just tried it and it came back undefined but if I didn't try it I would think logically that it would in theory return the value of the key 'name'.. Is that the point you're making there, making me see it like that? – James Jun 17 '23 at 10:58
  • 1
    @James you said it yourself, "logically it would return the value of the key" – theonlygusti Jun 17 '23 at 15:07

1 Answers1

3

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]);
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17
  • Thanks for that, but what's the difference, I mean why would you use static over dynamic and vice versa? Or is that a lot to explain? – James Jun 17 '23 at 11:00
  • @James added to the answer. if you find my answer useful don't forget to accept it (the checkbox) and upvote (the arrow up), thanks – Alexander Nenashev Jun 17 '23 at 11:08