1

Here's a broader example:

let someVariable = 1;
return {
  'Example String': 'example_string',
  'Example String 2': 'example_string_2'
}[someVariable];
lealceldeiro
  • 12,596
  • 4
  • 38
  • 67
Mladen
  • 367
  • 6
  • 18
  • See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). It’s an object with bracket notation access. – Sebastian Simon Aug 23 '18 at 13:06
  • You can't return in such a way as you'll get `SyntaxError: return not in function` – Sangsom Aug 23 '18 at 13:10

4 Answers4

4

That means you are accessing value of that particalar key in the object Ex:

someVariable = 'Example String';
{
  'Example String': 'example_string',
  'Example String 2': 'example_string_2'
}[someVariable];

above code will output:

example_string
Bhimashankar Mantur
  • 229
  • 1
  • 3
  • 12
2

Taking the code you posted as a sample for stating your point (it should be modified in a real app; see working snippet below)...

it returns the value associated to the key with value equal to the value of someVariable in the object

{'Example String': 'example_string', 'Example String 2': 'example_string_2'}.

In this case it will return undefined because there is no key in this object with name 1 (someVariable).

But if someVariable would be, for instance 'Example String', it would return example_string. See it below:

let someVariable = 1;

function getValue(key) {
  return {
    'Example String': 'example_string',
    'Example String 2': 'example_string_2'
  }[key]
}

console.log(getValue(someVariable));
console.log(getValue('Example String'));
lealceldeiro
  • 12,596
  • 4
  • 38
  • 67
0

Your example would return undefined, but if someVariable equalled 'Example String', it would return 'example_string'.

lealceldeiro
  • 12,596
  • 4
  • 38
  • 67
Alister
  • 21,405
  • 8
  • 36
  • 31
-1

It might be easier to understand if you rewrite it just a little:

let someVariable = 1;
let someObject = {
  'Example String': 'example_string',
  'Example String 2': 'example_string_2'
};

return someObject[someVariable];

It attempt to returns "index" 1 of the object, which of course doesn't work (since object doesn't have indexes).

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550