0

does anyone know what this syntax is in Javascript?

I got a function like so:

function myFunc(param) { 
  return {
     [var.prop]: param.func(args);
  };
}

That looks like a colon after an array. Would anyone know what that means in JS? Thanks.

Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
Eddy_Kay
  • 69
  • 5
  • Does this your question? (https://stackoverflow.com/questions/8246406/javascript-array-declaration-new-array-new-array3-a-b-c-create) – Mayur Jotaniya Dec 19 '19 at 10:45
  • Does this answer your question? [What do square brackets around a property name in an object literal mean?](https://stackoverflow.com/questions/34831262/what-do-square-brackets-around-a-property-name-in-an-object-literal-mean) – Nick Parsons Dec 19 '19 at 10:46
  • For future reference, if you have question about syntax, [this](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) is a good link to consult – Nick Parsons Dec 19 '19 at 10:48
  • Such semicolon in object literal is syntax error: `({a:1;})` → `SyntaxError: missing } after property list`. – myf Dec 19 '19 at 11:03

1 Answers1

1

In normal the object with key we know will be look like,

function myFunc() {
  const newObj = {
    'key': 'value'
  }
  return newObj;
}

console.log(myFunc());

In the above you can able to see that the 'key' act as a known string.

Suppose in your app if you get that string in dynamic format then you can add square bracket around like [] and can assign value of that property as a key to an object.

For eg.., You are getting the key from an object like,

const data = {
  prop:'dynamicKey'
};

And you need to assign the value of prop as key to an obj then you can use it like,

[data.prop]: 'value'

const data = {
  prop:'dynamicKey'
};

function myFunc() {
  const newObj = {
    [data.prop]: 'value'
  }
  return newObj;
}

console.log(myFunc());
Maniraj Murugan
  • 6,412
  • 10
  • 56
  • 92