Arrow functions and "this"

I’m working on refactoring my JS Calculator project to ES6 just to help solidify my memory of ES6. So I’m going around converting functions to arrow functions, and for a few that breaks it. Several of them have “this” in them, and I know the whole point of arrow functions is that they handle this differently, so maybe that’s it, but I’m not getting a handle on it.

Some areas of interest:

  • the “operation” function beginning on line 34: the “display an E if dividing by 0” part works, but the console.log I added to line 42 (inline, to keep the line numbers the same between the two versions) shows that that part doesn’t work. Is this big mess of ifs and elses just to complicated for an arrow function?
  • The function on li 93 breaks when I turn it into an arrow function. This has a this.
  • The function on li 144 is already broken, presumably because it calls the “operation” function above.

I’d also appreciate any other suggestions for things to consider in refactoring and cleaning up that I haven’t thought of. Thanks!

My understanding is that arrow functions are not a new and better way to create all functions. They are, to my understanding, a new shortcut to creating anonymous functions. They are not likely intended to be used in all situations.

Having said that, you could probably solve this issues (or some of them) by manually binding: for example, change line 107 to }).bind(this); to get the number to appear when clicked. You can read more about bind here


You might find the following articles helpful

When not to use arrow functions

Constant confusion: why I still use JavaScript function statements

To be clear, I’m not against using arrow functions. I love them actually. I’m just saying you need to be aware of when they are a good choice and when they may not be.

Hope that helps.