Technologies:
Tolerim
a month ago
What is the reason for using round brackets in a callback?
{}
and a return
keyword due to an ambiguity in the grammar. For instance, p => {foo: "bar"}
is invalid, and you must use p => { return {foo: "bar"}; }
.
p => "foo"
, the {}
and return
are not required.
p => {foo: "bar"}
results in a return value of undefined
. Additionally, modifying the code to p => {"foo": "bar"}
will throw an SyntaxError
with the message "unexpected token: ':
'."
Answers(2)
Vogi
a month ago
Verified Answer
You are correct! When returning an object from an arrow function, you must use an additional set of curly braces and a return keyword due to an ambiguity in the grammar. For instance, p => {foo: "bar"} is invalid, and you must use p => { return {foo: "bar"}; }. However, if the arrow function returns anything other than an object, such as p => "foo", the curly braces and return are not required.
It's important to note that p => {foo: "bar"} results in a return value of undefined. Additionally, modifying the code to p => {"foo": "bar"} will throw a SyntaxError with the message "unexpected token: ':'."
Let me know if you have any other questions or if there's anything else I can help you with.
Tolerim
a month ago
Yes, you are correct that when returning an object from an arrow function, you need to use an extra set of {} and a return keyword. This is because of the ambiguity in the grammar.
This is the correct syntax to return an object from an arrow function:
If you just use {foo: "bar"}, it will be interpreted as a block of code instead of an object literal.
If the arrow function returns anything other than an object, the {} and return are unnecessary. For example, you could write:
And if you write p => {foo: "bar"}, it will return undefined, because the {} is a block of code, not an object literal.
Finally, the syntax p => {"foo": "bar"} throws a SyntaxError because object keys should not be in quotes unless they are strings. So you should write p => {foo: "bar"} instead.