slevin
slevin

Reputation: 35

Confusion on Javascript Object's dot method

In Javascript, all keys in a property are strings, right? So, in other word,

this code:

var object = {
car: 'tesla'
};

and this code are same:

var object = {
'car': 'tesla'
};

But why is it so that I can access the key car using : object["car"] but not using this: object[car]

In other words, why do I need to put the key named car around quotes if the key named car has already been turned into a string?

I read this thread but couldn't manage to get a clear answer on this particular issue. Hope someone helps.

Upvotes: 1

Views: 103

Answers (1)

Quentin
Quentin

Reputation: 943510

Inside an object initializer, an identifier is treated as a property name.

The value used in bracket notation property accessors is an expression.

If you use an identifier in an expression, it is treated as a variable name.

Since you can use any expression in bracket notation, you can dynamically generate the value:

object[function_that_returns_car(argument_from_local_scope)]

object[`string with ${interpolated} value`]

object[i_from_for_loop]

… which is what makes bracket notation useful.

Compare to dot notation where you must use an identifier and that identifier is treated as the property name directly:

object.car

Upvotes: 4

Related Questions