Up the Food-I-mean-Prototype Chain


console.log( myEmperor["numLegs"] ); // should print 2
console.log( myEmperor["isAlive"] ); // should print true 


console.log( myEmperor[numLegs] ); // should print 2
console.log( myEmperor[isAlive] ); // should print true


console.log( myEmperor.numLegs ); // should print 2
console.log( myEmperor.isAlive ); // should print true

Can you explain to me the difference between these syntax?

I recall in previous lesson that these were the same statements, but clearly I'm missing something specific. Is it the context in which they're used?


The above is a literal key name, and a valid form assuming there is a numLegs property. If it does not exist, we can create it.

The above is a variable name, which may or may not refer to the "numLegs" property. By may, I mean, numlegs = "numLegs". We generally us a variable in a dynamic loop:

for (var key in object) {

The above is an indentifierName that is property specific. If the property does exist, it can be accessed. If it does not, it can be defined.

myEmporer.numWings = 2;

Now the 'numWings' property is defined.


I appreciate the reply.

I can't understand the way you put it though.

What's the difference between ["numLegs"], [numLegs], and .numLegs?

How come only ["numLegs"] within this context works? What are [numLegs] and .numLegs alternatively doing/saying/accessing?


The key names of an object are data type, 'string', even though we may write them without quotes provided they do not contain white space.

var object = {
    keyname: "some value",
    "key name": "another value"

When referring to a key name that exists, or that we wish to define, it is quoted within bracket notation syntax.


console.log(object["key name"]);

When referring to a key name contained in a variable, it follows we would not use quotes, else it will be a string.

var myKey = "keyname";


In the case of dot notation, we cannot use a variable in the notation. It is treated as a key name, proper.

console.log(object.myKey);      // object has no attribute, `myKey`

console.log(object.keyname);    // valid since object has an attribute, `keyname`

console.log(object."key name")  // cannot write quoted strings in dot notation.


I appreciate it. That was really helpful. Thank you!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.