2

I am trying to convert an arrow function into a regular function

this piece of code:

let rating = watchList.map( (item) => ({"title":item["Title"], "rating":item["imdbRating"]}) )

like so:

let rating = watchList.map( function (item) {
    "title":item["Title"], "rating":item["imdbRating"]
})

while I thought these two are equivalent, I am getting this message

SyntaxError: unknown: Unexpected token, expected

Eddie
  • 26,040
  • 6
  • 32
  • 55
esentai
  • 69
  • 8

3 Answers3

5

You are lacking return. When you pass in a custom function for the Array.map method, you will need to return a value for that function.

let rating = watchList.map(function(item) {
  return {"title":item["Title"], "rating":item["imdbRating"]};
})

Nonetheless, it is more useful to use the arrow functions, as arrow functions seems more concise, and allows you to access this within it.

wentjun
  • 35,261
  • 9
  • 79
  • 93
4

In arrow function any expression after => become implicit return of function.

In regular functions you need to use return keyword.And also warp your properties in {}

let rating = watchList.map(function(item){
    return {"title":item["Title"], "rating":item["imdbRating"]};    
}

You can also shorten your code by using Parameter destructuring.

let rating = watchList.map(function({Title:title,imdbRating:rating}){
    return {"title":Title, "rating":imdbRating};    
}

Or you could name to properties while destuctruing.

let rating = watchList.map(function({Title:title,imdbRating:rating}){
    return {title,rating};  
}
Maheer Ali
  • 34,163
  • 5
  • 36
  • 62
0

You need to use return and you can also use shorthand notation of object if you use destructuring

let rating = watchList.map(function({Title:title, imdbRating:rating}) {
  return {title,rating};
})
Code Maniac
  • 35,187
  • 4
  • 31
  • 54