Owen
Owen

Reputation: 23

Why can't a reference an old object when creating a new one

In the Chrome dev console, if I do this:

obj1 = Object({"a":"b"})

I can do this:

obj1.a
// -> "b"

But I can't do this:

Object({obj1.a:"c"})
// -> throws "Uncaught SyntaxError: Unexpected token ."

Why?

Upvotes: 2

Views: 40

Answers (2)

Sherman Szeto
Sherman Szeto

Reputation: 2405

Because thats awkward syntax. Obj1.c inside your last line wony be evaluated as a variable. It only accepts property names. Obj1.c is not a valid name for a property

Upvotes: 0

Jason W
Jason W

Reputation: 13179

Syntax error is because the object key cannot be directly evaluated in that notation. You'd have to do something like this:

obj2 = {};
obj2[obj1.a] = 'c';
obj2[obj1.a];

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

What is going on at a deeper level is the { } syntax is using an object initializer to construct the object. The property name of the syntax requires a name, a number, or a string literal. Evaluation of another object does not meet this requirement.

Upvotes: 3

Related Questions