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?
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