Why does bracket notation for accessing object properties work where dot notation doesn't?


#1



27. Looks For-In To Me


When I type my code using languages.variable it doesn't work, but languages[variable] does. Why is this?


Code that doesn't work:

var languages = {
    english: "Hello!",
    french: "Bonjour!",
    notALanguage: 4,
    spanish: "Hola!"
};

// print hello in the 3 different languages
for (var property in languages) {
    var variable = property;
    if (typeof languages.variable === "string") {
        console.log(languages.variable);
    }
}

Code that does work:

var languages = {
    english: "Hello!",
    french: "Bonjour!",
    notALanguage: 4,
    spanish: "Hola!"
};

// print hello in the 3 different languages
for (var property in languages) {
    var variable = property;
    if (typeof languages[variable] === "string") {
        console.log(languages[variable]);
    }
}

I thought that bracket and dot notation were one in the same - so why does bracket notation work here where dot notation doesn't?


#2

@cmkluza

Please see this thread (@mtf's posts) and this one. :slight_smile: You can think of dot notation as key-specific notation whereas bracket notation is more flexible and can accept variables, number strings, and other unusual inputs.