Search code examples
javascriptvariablespropertiesnotation

Use a property name stored in a var, dot and bracket notation


I'm on the bracket and dot notation challenge in JS, I understand (more or less) how it works, but I can't with a little point:

Why I can't use Dot Notation whwn a property name is stored in a variable?

This is undefined:

var car = {
seats: "cloth",
engine: "V-6"
};
var s = "seats";
function show_seat_type(sts) {
window.alert(car.sts); // undefined
}
show_seat_type(s);

This is OK

var car = {
seats: "cloth",
engine: "V-6"
};
var s = "seats";
function show_seat_type(sts) {
window.alert(car[sts]); // works
}
show_seat_type(s);

But why? Thanks guys.


Solution

  • By using dot notation, you indicate to the interpreter that there is a property of car that you know is named "sts". It doesn't attempt to resolve it. If you were to have an object

    var car = {
    seats: "cloth",
    sts : "foo",
    engine: "V-6"
    };
    

    Your dot notation code would work, but return the string "foo".

    Alternatively, by using the bracketed notation the interpreter expects a string, so any variable it receives will be resolved to a string. Now that you know that, consider this. How would you expect either of these calls to behave?

    car."sts"
    car["sts"]
    

    The first call errors out, and the second one returns "foo". Hopefully this illustrates the differences between these two methods of variable reference.