DEV Community

loading...
Cover image for A Super quick guide to arrow functions

A Super quick guide to arrow functions

Alex Nielsen
Returning to the tech industry after taking time off to be home with my young children. I have been sharing what I learn on my blog https://alexnielsen.net/
Originally published at alexnielsen.com ・2 min read

This is NOT a definitive guide to arrow functions. I’m writing a few other tutorials and blogs and want to have something to point people to so they can have a quick explanation and example of arrow functions since they are in so many of the modern frameworks. Just enough to be dangerous! To be clear, there are reasons where you should not use arrow functions, but they are not going to be discussed in this blog post. I just want you to be able to know how they work when you see them “in the wild”.

Let’s get started. I’m going to take you step by step converting a regular function into an arrow function.

Here’s a regular function using the function keyword
A regular old function

Let’s change that to an anonymous function expression
Function Expression

Should be nothing new here so far. No Arrows or ES6 yet, but here it comes…

First remove the function keyword and add the arrow
Basic Arrow Function

The only thing going on there is removing the function keyword and adding the arrow. And that’s it! You’ve gone and made an arrow function! Hurray! But wait, there’s more!

If there is only one argument, you can get rid of the parentheses around it.
Arrow function with parentheses removed

Getting pretty lean but we can take it even further. If the body of the code is only one line, we can get rid of the curly braces.
Arrow function with parentheses and braces removed

Frequently, you’ll see these used as a callback in another function so there is no const and no function name. This is the case that we see quite a bit and the real reason I wrote this all up in the first place
Anonymous arrow function

This doesn’t do anything on its own, but as a callback it’s useful. Here we’re using as a callback for looping over an array with the forEach array method.
Array.forEach with arrow function

As a comparison, here’s a regular old for loop. Sure, we understand this as programmers, but the arrow function just reads like a sentence in normal language. So much easier to understand!
Looping over an array with a for loop

I think that covers the basics. Again this is not meant to be the definitive guide, just an intro to figure out what they mean because we see them ‘in the wild’ in all the modern frameworks.

I added a video version of this blog. If you prefer video, check it out:
YouTube:

Discussion (1)

Collapse
mateiadrielrafael profile image
Matei Adriel

The real thing which makes arrow functions useful is the fact they preserve the context you define them in (aka they dont have their own this)

Forem Open with the Forem app