DEV Community

Sneha Jalukar
Sneha Jalukar

Posted on

Writing Arrow Functions in Modern JavaScript

Background

When I started learning JavaScript, one of the most confusing things -- especially when I was looking at snippets of code online -- was understanding how arrow functions are composed.

If you haven't written JavaScript code in a few years, or are new to functional programming, this may look strange at first, but don't let that intimidate you!

I hope this post serves as a quick and useful reference.

While a traditional function in JavaScript will look like this:

function(a,b){
  return a+b;
}
Enter fullscreen mode Exit fullscreen mode

Writing that as an arrow function would take that code snippet down to one line, as you'll see shortly.

How do you convert traditional functions to arrow functions? Just remember FABR!

  1. Functions - Drop the word "function"
  2. Arrow - Add the arrow
  3. Brackets - Remove the brackets
  4. Return - Remove the word "return"

Step 1: Drop the word "function"

The first thing you'll want to do is drop the word "function" from the word, as the ==> characters imply this is already a function.

Step 2: Add the arrow

Once you drop the word "function" then you'll also want to add ==>.

Continuing to work with the function we started with, it would look like:

(a,b) ==> { 
return a+b;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Remove the brackets

After this step, our almost-complete arrow function will look like:

(a,b) ==> return a+b;
Enter fullscreen mode Exit fullscreen mode

Step 4: Remove the word "return"

Finally, all that's left to do is take out the word "return" and we're done converting this to the arrow function syntax!

(a,b) ==> a + b;
Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope this post serves as a quick reference or good refresher if you're new to the world of JavaScript / web development.

For more examples, the MDN Web Docs are a great place to look: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

Stay safe, and stay curious!

Top comments (0)