Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert arrow function into a regular function?

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

like image 446
esentai Avatar asked May 13 '26 03:05

esentai


2 Answers

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.

like image 137
wentjun Avatar answered May 14 '26 15:05

wentjun


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};  
}
like image 43
Maheer Ali Avatar answered May 14 '26 15:05

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!