Reputation: 20232
In my react code, I have the following method which returns a hash:
foo: function() {
return {{a: 1,b: 2,c: 3}, {d: 4}};
}
On the line with the return
statement I am getting this however:
Parse Error: Line 141: Unexpected token { while parsing file
Why is this occurring?
Upvotes: 0
Views: 1159
Reputation: 2127
You are getting that error because when the parser sees the first '{
', it expects to find a key next, but instead finds another '{
', which is invalid syntax. Refer to the proper syntax for Object Literals.
Since there's nothing descriptive enough in the provided code to tell what you're trying to return beside that you're trying to return a hash, I can only guess that you are either intending to return 4 named numbers:
return { a:1, b:2, c:3, d:4 };
or two nested objects with named numbers; in which case you must provide a key for each nested object:
return { nested_a: { a:1, b:2, c:3 }, nexted_b: { d:4 } };
To understand why, think about the code that will be receiving the returned value from your foo
function.
var foo_result = foo();
If you want to access a
, for example, how would you reference it? With the original object you are returning ({ { a:1, b:2, c:3 }, { d:4 } }
) there would be no way to reference that first inner object containing a
, b
and c
.
var a_result = foo_result.?.a; // no way to get at that variable
Which is why every property in an object needs a key. Following my example above:
var a_result = foo_result.nested_a.a; // this works
When you see an array literal declared like:
var an_array = [ { a:1, b:2, c:3 }, { d:4 } ];
This is ok because arrays have an implicit way to reference their elements; by their index.
var a_result = an_array[ 0 ].a; // array indices start at 0
Upvotes: 2