Why we access a key value in for/in loop like that? (JavaScript)

Hello, let’s say we have an object like this one:

const object = {
  key1 = 1,
  key2 = 2,
  key3 = 3
}

And I want to access all of his values by console logging thems. I know I would need to do this like this:

for(let key in object) {
  console.log(object[key])
}

But why we are accessing the value of each key with this syntax object[key], not object.key?
If we would console.log(key) in this for/in loop it would represent the name of the property (like “key1” for example) but when we are trying accessing the value of the key not within for/in loop like object[key1] it’s not working so why is it working in for/in loop?

You should separate keys and values in the object with column, not equal sign:

const obj = {
  key1: 1,
  key2: 2,
  key3: 3,
};

You can learn best about dot- and bracket- notations here:

It will not work inside for ... in loop either. Try this outside your loop and see if it helps to understand:

let key = 'key1';
console.log(object[key]); // 1
1 Like

Hello @bartekw2213,

for a detailed explanation have a look at the Working with objects article from MDN.

A simple and superficial explanation is that you need bracket notation when you are accessing an object property through a variable; use the dot notation when you want to access a property using the literal key.

So with this example:

const o = {
 dog: "pitbull"
}

// you can access it literally because you know the key value
o.dog // pitbull

// or through a variable
var accessKey = "dog"
o[accessKey] // pitbull

Hope this helps :+1:

2 Likes