Burt Burt - 2 months ago 6
Javascript Question

Javascript bracket notation to access a property/key stored in another variable

So I'm going through the YDKJS series and I came across this bit that I would like more help understanding this:

"Of course, bracket notation is also useful if you want to access a property/key but the name is stored in another variable, such as:"

var obj = {
a: "hello world",
b: 42
};

var b = "a";

obj[b]; // "hello world"
obj["b"]; // 42


I'm having trouble understanding the var b = "a"; part. Why isn't b it's own variable that contains the string "a"? It's outside the scope of obj but it's referencing the variable in obj? And how is it that the var b is now a part of obj and you can use obj[b] to reference it?

Answer

All properties can be access through bracket notation, and the property name as a string. Consider this:

'Hello world'.length 

Is equivalent to:

'Hello world'['length']

As you can see, the property can be access by brackets and a string representation of the property. So in the example:

var obj = {
    a: "hello world",
    b: 42
};

var b = "a";

obj[b];         // "hello world"
obj["b"];       // 42

The variable b just stores the string 'a', which is then used like this:

obj[b] == obj["a"]

Above, obj[b] is the same as obj["a"].

You have become confused. Variable b and "b" are not associated. Variable b has the value of "a".

The 'a' is just substituted in, which access the a property, returning 'Hello world'. The second access the b property returning 42