1

why in this code, a is interpreted as real key name, not value hidden under a variable?

function myfunc(a,b)
{
return {a:b};
}

var c = myfunc("key","value");
console.log(c);

This code print:

{
  a: "value"
}

not:

{
  "key": "value"
}

How to modify this code, to use value under a as key name?

sosnus
  • 968
  • 10
  • 28

2 Answers2

0

It happens because {}.a means property a of the object and doesn't refer to any variables you have. In order to use some variable as a key, you need to use [a] instead. You may read more on this topic here.

function myfunc(a,b)
{
  return {[a]:b}; // note I added [ ]
}
Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
0

You need to use the [bracket notation] for a computed property name

function myfunc(a, b) {
  return {
    [a]: b
  };
}

var c = myfunc("key", "value");
console.log(c);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34