How to use variables in dot notation like square bracket notation

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"?

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.


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"]

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.

Tags:

Javascript