Arrow Functions

this rule of thumb

B. Chepkorir
SD Tidbits
2 min readNov 14, 2022

--

Photo by Jan van der Wolf from Pexels

Arrow functions are godsends for many reasons. Possibly, because they often let us do much with less:

  • less parentheses
  • less braces
  • less lines of code

…and they still retain much of the capabilities of anonymous JavaScript functions. Except for some special limitations.

These limitations may seem like handicaps, but they might be by design. One useful and often seen limitation is that they don’t have their own this context— a characteristic of method functions.

Fact: it’s best not to think of them as methods

How is this useful?

For creating object or instance functions that need access to a more global this in a particular context. Like in a JavaScript class or browser.

We can define a function in an object literal that needs to be executed in a different context, and still behave as expected. Like an object created based on an interface rather than a class in TypeScript.

Another example:

The objects shaken and stirred can both be accessed from the ArrowClass. However, only the shaken arrow function will reference the ArrowClass context when looking for appService. The stirred anonymous function will reference its own object’s context. So, it will look for appService within the stirred object where it has been defined in.

🤔Are the classes here, ArrowClass and AppService, depicting best practices? Probably not. The variable a could exist in the literal objects themselves because it contains basic primitive data. If the data were more complex, then we’d need to consider whether we want it…shaken not stirred. 😋

--

--

B. Chepkorir
SD Tidbits

Software Development Enthusiast | Writer on Code Like A Girl & FreeCodeCamp -- I "talk" fast