In Functional Programming exercise 7, we are tasked with using of the map method. While I was able to understand map method, there is something that confuses me about how arrow function returns object. Why are parentheses required when returning value using arrow function here?
For example: const ratings = watchList.map(elem => ({mapMethodTitle: elem.Title}));
will return [{"mapMethodTitle":"Inception"},{"mapMethodTitle":"Interstellar"},{"mapMethodTitle":"The Dark Knight"},{"mapMethodTitle":"Batman Begins"},{"mapMethodTitle":"Avatar"}]
However if we omit parenthesis like const ratings = watchList.map(elem => {mapMethodTitle: elem.Title});
it will result in [null,null,null,null,null]
In normal functions we can just return obj on its own:
let funcMetascore = function(elem) {
return {funcMetascore: elem.Metascore,ID: elem.imdbID};
}
arrow functions work in two ways, implicit return, of explicit return
with explicit return you have as usual the curly brackets around the body of the function
(...parameters) => {
// do stuff
return result;
}
implicit return can be used when the function is of only one line:
x => x+2
but you can’t return an object in the same way as it will recognise the curly braces as those of the body of the function, and it will not work (it returns null because the function doesn’t run)
to make this work, you need to wrap the object in round parenthesis, so that the curly braces are not recognised as those of the function body