0
let obj = {
  a:10,
  b:20,
  c:true,
  d:null
}

for(let key in obj) {

  //console.log(key);

  //console.log(obj.key); //4 undefined

  console.log(obj[key]) // 10 20 true null //work
}

why dot notation giving me undefined.

I`m newbie started learning js.

6
  • 3
    Because there is no key named "key" on the object, the options are a, b, c, and d but not key Commented Aug 11, 2022 at 7:47
  • 2
    @mousetail key is the name of the for-loop variable, iterating on the keys of the dictionnary. Commented Aug 11, 2022 at 7:50
  • 4
    obj.key and obj["key"] are equivalent and not to be confused with obj[key]. Commented Aug 11, 2022 at 7:50
  • 1
    @BenjaminRio obj[key] vs obj["key"] Commented Aug 11, 2022 at 7:51
  • but key has a,b,c, and d values, I was expecting that it would be obj.a, obj.b, obj.c and obj.d. I`m I expecting wrong? Commented Aug 11, 2022 at 7:53

1 Answer 1

1

The for-loop iterates over the dictionnary keys. Therefore, key is a string.

You can access value of key a element using obj["a"] (notice the apostrophes) or using obj.a(notice the absence of the apostrophes).

Since key is a string obj.key does not work (in the first iteration it computes obj."a").

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.