How to use variables in dot notation like square bracket notation

Solution 1:

You can't use variables in dot notation (short of using eval, which you don't want to do). With dot notation the property name is essentially a constant.

myObj.propName
// is equivalent to
myObj["propName"]

Solution 2:

The short answer is: you can't access a property using dot notation unless you know the property's name.

Dot notation also puts a restriction on the property names you can access because the property name must be a valid JavaScript identifier. For example, if you had a property called my prop (or better yet, my%prop) then it would not be possible to access it without using bracket notation because it would lead to a syntax error is most cases.

The Member Operators page on MDN explains this a bit further.

As an aside:

Wouldn't it be a little confusing to be able to dynamically look up properties using dot notation?

item.x // is this the property "x" or do I have to look up variable "x"?

Solution 3:

If you use numbers to access an array you have to use the brackets:

item[0]

var k = 0;
item[k]

as

item.0

doesn't work (wrong syntax).

If you use a string

item["key"]

var p = "key";
item[p]

equals

item.key

In the latter context

var p = "key";
item.p

would cause a wrong output as p is not treated as a variable here.

Solution 4:

the dot notation is limited to certain chars ... see this question ... the square bracket notation allows you to break that limitation:

var item = {};
item['very long variable name containing empty spaces ... and dots...'] = 'valid var';
item.1 = 'not valid var'; // will not work;
item['1'] = 'valid var'; // will do just fine...

Solution 5:

You actually can now.

In this case you can use square brackets to use a variable for dot notation.

console.log(item.[x])

This is especially useful for use in Typescript.