Here's a broader example:
let someVariable = 1;
return {
'Example String': 'example_string',
'Example String 2': 'example_string_2'
}[someVariable];
Here's a broader example:
let someVariable = 1;
return {
'Example String': 'example_string',
'Example String 2': 'example_string_2'
}[someVariable];
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
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'));
Your example would return undefined
, but if someVariable
equalled 'Example String'
, it would return 'example_string'
.
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).