In JavaScript, if you have the following code:
var map_id = 100;
var myobj = {};
myobj[map_id] = 6;
var myobj2 = { map_id : 6 };
console.log(myobj, myobj2);
The console output is as follows:
{ '100': 6 } { map_id: 6 }
Questions:
- Why does JavaScript syntax work differently in these two different cases - why is they key in
myobj2
set to the literalmap_id
rather than100
? What is the reasoning behind having this difference? - Is there any way to set the key to the value of the
map_id
variable in a compact, one-line way, rather than having to define the object separately first?
Thanks.