1

I saw a javascript expression like this:

var foo = {...}[...];

can anyone explain what that means?

Best Regards

Update:

this is a code example:

var ENV_PRODUCTION = {
  production: true,
  development: false
}[process.ENV.NODE_ENV|| 'development'];
5
  • 1
    Please provide a working example, empty object and empty array (var a = {}[]) gives syntax error, so it's not valid. Commented Oct 13, 2016 at 8:09
  • 1
    Was it actually an array (as in [1,2,3]), or just something that would evaluate to a property name? You've simplified the expression too much. Commented Oct 13, 2016 at 8:09
  • 1
    var values = {key1: 'value1', key2: 'value2' }; var key = 'key1'; var foo = values[key];? Commented Oct 13, 2016 at 8:11
  • Can you share the exact code? Commented Oct 13, 2016 at 8:14
  • 1
    x = { foo: 42, bar: 'baz' }['foo'] is an immediately invoked object literal. Commented Oct 13, 2016 at 9:22

3 Answers 3

4

It will return the inner value by key value see:

var foo = {
 "1": "Jam",
"2":"Stuff"}[1];

var bar = {
 "1": "Jam",
"2":"Stuff"}[2];

var foo = {
 "1": "Jam",
"2":"Stuff"}[1];

var bar = {
 "1": "Jam",
"2":"Stuff"}[2];

var jam = {
 "1": "Jam",
"B":"Other Stuff"}['B'];

var foobar = {
 "...": "...",
"B":"Other Stuff"}['...'];

console.log(foo, bar, jam, foobar)

Further documentation

Sign up to request clarification or add additional context in comments.

Comments

1

Its a reference to element of the object.

Try in console:

var x = {a:1}['a'];

x = 1

Comments

0

This is a spread operator as per ES6

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

4 Comments

I suspect the ... in this case is just a simplification by the OP and is meant to represent other stuff, rather than be the spread operator.
@JamesThorpe oh..ok. I guess then OP should show the exact code.
I think isn't destructuring, probably @Newton answer is correct. Could you provide an example of your assertion?
@Hitmands sorry, not sure if I can give a relevant answer unless you share the exact code that you saw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.