arrowFunctions () => (simplified)

Kendall Stephens
2 min readNov 11, 2020

Rest assured that you are not alone if seeing JavaScript’s arrow function syntax for the first time had you making this face…

But if you can set aside that strange syntax for a moment you will find that, when appropriate, using the arrow function expression provides a compact alternative to a traditional function expression.

Take a look at the examples below to see for yourself!

Traditional Function Syntax
Arrow Function Syntax

Both examples above use the forEach iterator to display the items from the CoffeeArr. The second example makes use of the arrow function(=>), which allows us to ditch both the function call and the curly braces making the syntax a bit shorter while providing the same results. Pretty cool!

Not exactly life changing, but there are instances where this approach can save you from writing quite a few unnecessary lines of code. Take a look at the example below which uses promise chaining to return coffee of a certain price. This can be a bit bulky using traditional function syntax.

Traditional Function Syntax

Now, let’s use our new found knowledge about the arrow function to refactor this code and save ourselves some typing! We’ll go ahead and remove the function expressions, our brackets and add in our arrows between the arguments and the bodies. This time let’s also take advantage of another perk of arrow functions, “implicit returns”. This allows us to omit the “return” keyword and implicitly return the value.

Arrow Function Syntax

The result is much cleaner, and saves us a good amount of typing.

Ok, so when should you be using arrow functions?

Arrow functions are best suited for callbacks or methods like map, reduce, or forEach.

There are also certain instances where it’s best not to use an arrow function, such as…

  • Object methods
  • Callback functions with dynamic context
  • Anytime they make your code less readable

If you are a new software developer like myself, I hope this has cleared up some of the mystery of the arrow function for you. Thanks for reading! :)

--

--