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,593
  • 6
  • 36
  • 58
esentai
  • 69
  • 1
  • 10

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
  • 40,384
  • 10
  • 95
  • 107
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
  • 35,834
  • 5
  • 42
  • 73
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
  • 37,143
  • 5
  • 39
  • 60