0

I am trying to construct a javascript object as follows :

function returnA(){ return "A" }

function returnB(){ return "B" }

Now when I try,

obj = {returnA() : 1, returnB() : 2}

it gives me syntax error.

On the other way, when I do

obj = {};
obj[returnA()] = 1;
obj[returnB()] = 2;

It works perfectly. Why the first method of object initialization doesn't work, while the second one work ? Does there any difference in the time, when both are executed, I mean by that does first initialization takes place during compilation phase(static binding), while second initialization takes place on the fly, during runtime ?

Please help me out, as I am new to javascript.

Thanks in advance.

Edit : I needed to know the reason behind why it's happening. So, this question is different from the one marked as duplicate.

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97

1 Answers1

1

obj = {returnA() : 1, returnB() : 2} , this obviously gives an error you can't assign to a result of a call.

obj = {};
obj[returnA()] = 1;
obj[returnB()] = 2;

this works because returnA() and returnB() will return a string which will become property names of the object

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24