I am with a confusion between the use of "object.property" vs "object[property]"
I loop through the text string. (I will only talk about the first cycle)
1- The first console.log returns the letter (h)
2- The second console.log returns the value 1, from the "h" property of the "counts" object
3- Taking into consideration that it par[i]
is "h" and that "h" exists in the "counts" object, why does it throw me an error when using counts.par[i]
what is technically the same as saying ?counts[h]
let par = "hola"
let counts = {
h:1
};
for(let i=0; i<3;i++){
console.log(par[i]) //Devuelve "h" "o" ..etc
console.log(counts.h) //Deuelve 1. El valor de la propiedad "h" en el objeto counts
console.log(counts.par[i]) //Devuelve que no esta definido
}
The square brackets are useful when the property name is dynamic, for example if it is inside a variable
objeto["valor_de_la_variable"]
. This cannot be done with the notation of.variable
When we use square brackets in a string, the latter is treated as the
object
["h","o","l","a"].So
par[o]
we can use it as a property name if we use it inside square brackets[par[o]]
, we can't use it in the notation of.propiedad
.Basically there is no difference, just that the form object[property] can be accessed using a variable in the square brackets.
Count pair does not exist in your statement. That's why it gives you an error.