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.

Max Joy
  • 1
  • 1

1 Answers1

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").

Benjamin Rio
  • 652
  • 2
  • 17