Is this being used to store a variable within a function?

Is there a practical reason for not using let total in the scenario below? I understand that the purpose is to illustrate how arrow functions address the this issue, but are there real-world use cases where this solution is beneficial?

function sum() {
  this.total = 0;

  arr.forEach((item) => {
    this.total+= item;  // everything works fine since `this` refers to the outer function
  })
  return this.total;
} 

Answer №1

Using local variables makes sense in the scenario mentioned above. However, utilizing arrow functions with lexical scope has a broader range of applications.

In today's development landscape, frameworks are commonly used for projects which include components. Variables exist at the component level and are then linked to the HTML elements.

class component {
  constructor() {
   this.data  = {};
  }
  // For instance, if you retrieve data and need to assign it to this.data
  getData() {

      somePromise.then((res) => {
        this.data = res // you can access the parent object without any issues
      })
  }     

 }

On the other hand, when dealing with normal functions:

  getData() {
      const self = this; // save the parent reference to a local variable
      somePromise.then(function(res) {
           self.data = res // now you can set the data as the function's 'this' is different here
      })
   }

There are alternative approaches as well. You can bind an anonymous function with 'this' using the native bind function, allowing you to access the correct context within the function.

Therefore, in practical terms, arrow functions have effectively resolved this dilemma.

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

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

Unlocking the Power of Global Props in AlpineJS: A Step-by-Step Guide

I'm currently exploring AlpineJS after having some experience with React and basic knowledge of Vue. One thing that has puzzled me about AlpineJS is how to update a state value from within a function, similar to how it's done in React. Let' ...

"Troubleshooting: jQuery Find function not functioning correctly with HTML template

I am having trouble with a Shopify liquid code that I am trying to load into an HTML template <script type="text/template" id="description"> <div class="product-ddd"> {{ product.description }} </div> ...

Is there any way to extract the source files from a compiled Electron application?

Is there a way to extract the contents of a .app Application developed using Electron for Mac OS? I'm eager to explore the underlying source files, but I'm not familiar with the procedure to access them. Any assistance would be greatly appreciate ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

Error: The PDFJS variable is not recognized when trying to load a PDF file

I've been experimenting with pdf.js to load PDFs into a web application in order to extract information in real-time. However, I keep encountering an error even with a simple example. I've attempted enclosing the code in $(document).ready() as a ...

Arranging search findings based on relevance using javascript

I'm developing a personalized search feature. Currently, when I type "The R," the search results list starts with The Fellowship of the Ring because the phrase "the ring" is in its .text property. However, I want The Return of the King to appear first ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...

node.js is reporting that it cannot locate some of the modules

Attempting to execute a file using node run index.js within the flashloan test folder results in an error that keeps occurring... node:internal/modules/cjs/loader:1042 throw err; ^ Error: Cannot find module '/home/schette/Documents/flashloan test ...

Using a JavaScript variable within an AngularJS scope

Currently in the process of building a webpage with the MEAN stack, I utilized the HTML5/Javascript sessionStorage variable to store the user data for access across all pages. Now, the challenge is passing this data into angularJS through the controller w ...

Working on executing various methods with a JavaScript client on a Flask RESTful API that requires authentication

I'm currently developing a JavaScript client-side app to interact with a Flask RESTful API. I've implemented some methods that require user authentication, but for some reason, even after logging into the server, I receive a 401 error (Unauthoriz ...

Having Trouble with Click Function: Loading Pages into Div using Jquery/Ajax

Struggling to load content from other pages into a specific div by clicking on a URL link? Despite having previously executed the code successfully, it seems to redirect to the linked page instead of loading in the desired div. Even with an alarm set up as ...

"Getting an 'Undefined index' error while accessing a JavaScript variable in PHP

Every row in my table contains an Edit button. I managed to fetch the row number by clicking on the Edit button using JavaScript, but I am unsure how to do it in PHP. My attempt to pass the variable from JS to PHP resulted in an error: Undefined index ...

Why is the second row of inputs not displaying in Vue.js?

I am currently developing a Single Page Application (SPA) that includes options with variants, similar to the image shown below: [1]: https://i.sstatic.net/82I5U.png However, I have encountered an issue where the second row of inputs for variants is not b ...

What is the best way to access and retrieve object properties in JavaScript?

Hey there! I'm working on a project using React with the React Context API. My main component is App.js, which is a functional component containing the app's logic. Within this component, I've set up state using useState for context: const ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

What is the method for deactivating a form input field in Angular Formly?

Is there a specific way to disable a form input field using Angular Formly? I have tried searching online and cannot find a clear answer. Even after checking Formly's 'field configuration docs', I only found one mention of the word 'dis ...

Generate - Create 2 different versions of the web application

Currently, I am in the process of learning Grunt and exploring ways to generate 2 variations of an application with different configuration settings. My goal is to have one version where a boolean in a specific .js file is set to false, and another versio ...

Issue with Jquery event not triggering correctly following ajax data retrieval

This script uses jQuery and Ajax to populate a navigation bar with categories and subcategories dynamically. The first unordered list is static, while the second one is populated after receiving data via Ajax. There are some jQuery events that need to be i ...