Accessing object property using for loop?

Hi all,
Hope everyone is okay. Please explain why (source.i) results in “undefined”?

let source = { "apple": 1, "bat": 2 }

for (let i in source) {
    console.log(i)
    console.log(source.i)
  }

//Console:
apple
undefined
bat
undefined

If ( i ) points to the correct key, why is ( source.i ) not plausible?

Challenge: Intermediate Algorithm Scripting - Wherefore art thou

Link to the challenge:

Hi, replace dot with braces: [] and it will be fine.
There are several steps in JS section about difference between dot and braces. I can’t remember which steps exactly.
If I am not mistaken if you are using variable to accesss prop, you need braces, full stop.

some test:

let source = { "apple": 1, "bat": 2 }

for (let i in source) {
    console.log(i)
    console.log(source.apple)
  }

Output:

apple
1
bat
1
2 Likes

Thanks, that was a giant, silly mistake from me. I tried brackets and saw:
//Console:
apple
1
bat
2

With using brackets I thought the output was counting the length of the object but that would have been (0, 1) not (1,2).

Lesson learnt, be more focused when stepping through code. I feel silly and thank you very much. I’ll read up on the difference between dot and braces again.

Don’t feel that way, this coding stuff is not easy)

1 Like