Search code examples
javascriptobjectpropertiesnotation

javascript - dot vs bracket notation in enumeration


I do know there's some differences between dot and bracket notations but for this specific problem I am a bit confused why the dot notation wouldn't work and bracket does.

var rockSpearguns = {
  Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
  Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
  Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
  Firefork: {barbs: 6, weight: 8, heft: "overhand"}
};

function listGuns (guns) {
    for(var speargun in guns){
        console.log("Behold! "+speargun+", with "+ guns[speargun].heft +" heft!");
    }
}

the part I am a bit confused is guns[speargun].heft this would work properly but if I do guns.speargun.heft then it will be undefined.

Since the properties in the rockSpearguns are all just one word shouldn't gun.speargun still able to call out the properties too?

I have thought a bit was the reason because now speargun is a string that if putting into gun.speargun it actually becomes something like gun."speargun" because if using bracket notation we just do gun[speargun] instead of using gun["speargun"] because this will just make it a double quote which is wrong.


Solution

  • It is not working because there is no speargun property in the rockSpearguns object.

    The reason is that in a JS object, all property keys are strings. When you use dot notation, JS is thinking you are looking for a key with the explicit key of whatever is after the dot.

    In your code var speargun is being replaced with a string value of each of the properties inside the rockSpearguns object.

    So, guns[speargun].heft translates to guns["Sharpshooter"].heft

    I suggest you to read this article.