Beware of using implicit returns in arrow functions.
Consider the below example of a simple arrow function. It returns a simple variable. In the absence of any other statement in the function body, a simple mention of x
will return the value of x
.
|
|
Let’s modify the block. We now want to return an object with the input value within it.
|
|
Oops.. We expected {x: 1}
but got 1
because the flower brackets were treated as enclosing a function body and not an object.
To get an object, we have to do a simple change -
|
|
We have used double brackets to signify that the return variable is an object (and to indicate that the flower bracket is not meant to start a function body).
Or, we could simply follow a consistent pattern of always using an enclosed function for any and all arrow functions.
|
|
The last option is the safest, but is not popular with lazy folk (of which I am an active member).