0

difference between "." & "[]"

difference between "." & "[]"

Unni
  • 17
  • 3

1 Answers1

1

You have no "key" attribute to your object. Hence the undefined. object.key would be defined only if your object contained a 'key' field. object.afaque for example is 95. But it needs to be literal afaque. You cannot access a field with . operator from a variable containing field name. You can do that with '[]' operator tho.

What you want to do is probably

for(let key in object){
   console.log("Marks of", key, "are", object[key]);
}

Difference between both is that one precisely.

in A[B], B is an expression that is evaluated to a key (a string in your case), and A[B] is the value associated to that key in A. If you wanted to use A[B] notation with a static field name, you would need to enclose that field name into double quotes. Because it is a string value. object["lafaque"] for example.

in A.B, B is an attribute name. It is part of javascript syntax. Like a variable name for example. Like in the expression key=12;. Typing that, you expect the variable key to be set to 12. Not the variable afaque because value of key would be "afaque". key in both key=12 or object.key are not strings. It is the "key" identifier, parsed and interpreted by the language as a variable name in the 1st case, or a field name in the 2nd.

in object["lafaque"], "lafaque" is a string. As in object["la"+"faque"] or object[key] or object[convolutedWay("to", compute, "a string")]

chrslg
  • 9,023
  • 5
  • 17
  • 31