Transforming an arrow function into a traditional function: What's the process?

I am currently attempting to convert an arrow function into a regular function.

This is the code snippet I am working with:

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

The goal is to rewrite it as follows:

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

Although initially I thought these two versions were equivalent, I encountered the following error message:

SyntaxError: unknown: Unexpected token, expected

Answer №1

Your code is missing the return statement. When you provide a custom function for the Array.map method, remember to include a return statement in that function.

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

Instead of traditional functions, arrow functions are preferred as they are more concise and allow you to access this within them.

Answer №2

Arrow functions automatically return any expression after the =>.

In standard functions, you must use the return keyword and wrap your properties in {}.

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

You can also simplify your code using Parameter destructuring.

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

Alternatively, you can name the properties during destructuring.

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

Answer №3

To achieve this, utilize the return statement along with the shorthand notation of objects when employing destructuring.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The meter.value update feature is functioning properly, however, it does not refresh the displayed "hover" value

When using JavaScript to update a meter's value, I encountered an issue: var LFRMSMeter = document.getElementById("LFRMSMeter"); LFRMSMeter.value = parseFloat(j[0]); Although the updating of the value works fine, hovering over the meter displays the ...

Trouble with Saving Compare-Object Results to CSV

I am attempting to compare data from two pscustomobject arrays and save the non-matching data into a separate array, which will then be exported to a CSV file. Here is the code snippet I have: function DataCompare { $NotMatch = @() #Compares the two array ...

Modify the div's width from 100% to 1000 pixels when it is less than 1000 pixels, using Javascript

I need help with writing Javascript code that will change the width of a div element called "red" from 100% to 1000px when the browser width is less than 1000px. The code should revert the width back to 100% when the browser width is greater than 1000px. ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

The totalVowels count is stuck and not changing

My function seems to be having trouble updating the totalVowels variable. Currently, I'm splitting the argument into an array, iterating through it, and incrementing totalVowels when there's a match with my vowel regex pattern. I've tried t ...

What is the expected result of running this Javascript program with asynchronous tasks?

My expectation with this code is that it will run, then after a 2-second delay, the execution stack will become empty with one callback in the setTimeout function. Since the promise is not resolved yet, I anticipate both the message queue and job queue to ...

Utilizing an array of objects to import images

Within the data file, there exists an array of objects where icons are described as properties of these objects. The question arises: how can we utilize these icons as links? export const socialLinks = [ { url: "https://www.youtube.com", ...

What is the best way to observe a function and provide a simulated result from within a different function using jasmine?

Query: How can I access the reference of getWindowSize within getBreakpoint() to perform spying on it? Additionally, how can I use callFake to return mock data? media-query.ts export const widthBasedBreakpoints: Array<number> = [ 576, 768, 99 ...

Utilizing JSON format for processing HTTP requests in JavaScript with Node.js

I'm working with a snippet that retrieves data in JSON format, but I'm interested in manipulating the data instead of just outputting it to the console. var request = require('request'); var headers = { 'Connection': ' ...

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...

Is there a way to stop a for-in loop within a nested forEach function in JavaScript?

I am facing a situation with nested loops for (var key in params) { if (Array.isArray(params[key])) { params[key].every(function(item) { let value = something(item.start, item.end); if (value === item.start || value == item.end) { ...

Addressing the problem of refactoring in JavaScript when associating arguments with keys in MongoDB

I am facing a dilemma with two functions that are almost identical except for the value being set as indicated: function extracted_start(details, txt) { return FutureTasks.upsert({ number: details.number ...

Issue with import alias not functioning within route grouping in Nextjs

Exploring the use of route groups and nested layout files led to encountering a "module-not-found" error with every import that used "@". Here is my jsconfig.json setup: { "compilerOptions": { "baseUrl": "./src", &q ...

How can I modify the style of table rows with CSS?

Is there a way to change the color/background of a selected row just like it does on hover, and also have the option to deselect the row? To see how it looks on hovering, check out: http://jsfiddle.net/q7ApN/ If you want to make a Change: #gradient-styl ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

Having trouble loading the image source using JSON in Vue.js

var topArticle=new Vue({ el:'#toparticle', data:{topmostArticle:null}, created: function(){ fetch('topnews.json') .then(r=>r.json()) .then(res=>{this.topmostArticle=$.grep(res,functi ...

Angular 2 patiently checking for a function to provide a result before proceeding with the next function

Just starting out with Angular 2 here. I have two services, let's call them location and price for this example. The location service retrieves the currency code and symbol based on the user's IP address. Here's an example of what it return ...

populate the empty slots in an array with the correct numbers

Having two pre-sorted arrays as shown below: [1,2,4,5,8] [x,x,x,x,x] The goal is to fill in the missing elements with 'y' in the corresponding array, resulting in: [1,2,3,4,5,6,7,8] [x,x,y,x,x,y,y,x] Although the data arrives separately, they ...

'This' term within a CoffeeScript class

I have created a class in CoffeeScript: class PresentationFramework constructor: (framework) -> log.info 'Looking for presentation framework module: ', framework @template = fs.readFileSync path.join(framework, 'templ ...

Is the 404 page being utilized as a fallback for AJAX requests?

I am looking to create a one-page website that utilizes history.pushstate to modify the URL. My plan involves having only one HTML file for the site, which would be the 404 error page. This setup would redirect users to that page regardless of the URL they ...