-2

In the following example we are accessing properties of an object but why does accessing the object with the Member Access throw an error:

 var d = {a: 10, b: 20, c:30};
         
         var keys = Object.getOwnPropertyNames(d);
         
         for(let i = 0; i < keys.length; i++){
            console.log(d[keys[i]]);
            //console.log(d.keys[i]); //throws error
         }

For example shown above, I would assume this would be because if we accessed it with the member access operator it would try to access d immediately without initializing keys[i]. Would this be correct?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • @jabaa If you look closely i said: "why does accessing the object with the Member Access throw an error:" I never said the code throws an error. Read again. (he deleted his comment) – handsome-and-SKINNY Mar 08 '22 at 19:01
  • 3
    It's because the object `d` doesn't have a key `keys`. `d.keys[i]` is equivalent to `d['keys'][i]` – jabaa Mar 08 '22 at 19:02
  • 1
    @jabaa no; `d.keys[i]` is equivalant to `d."a"` or `d."b"`. If you do `d['keys'][i]` you're trying to access an item from the array in keys `{ keys: [1, 2, 3] }`. – code Mar 08 '22 at 19:05
  • 2
    @code That’s not true; jabaa’s comment is correct. `d.keys[i]` is equivalent to `d["keys"][i]`. If `i === 0`, it’s equivalent to `d.keys[0]`. There is no `keys` key; that’s the root of the error when attempting to access `0`, or `i`. – Sebastian Simon Mar 08 '22 at 19:19

1 Answers1

2

At first, d.keys is tried to be accessed and find item at index i. See what happens if there is an item inside d named as keys:

var d = {
  a: 10,
  b: 20,
  c: 30,
  keys: [1, 2, 3, 4]
};

var keys = Object.getOwnPropertyNames(d);

for (let i = 0; i < keys.length; i++) {
  // console.log(d[keys[i]]);
  console.log(d.keys[i]); //works if finds any property named keys
}