Arrow functions

In JavaScript, you see a lot of callback functions. Those are functions that are passed as a parameter to other functions. Most of the loops you’re about to learn depend on callbacks.

Like most pre-ES6 code, functions are wordy. You have to explicitly declare that you’re creating a function with the function keyword, add curly braces to signify the body, use return statements to end the function, and so on. It’s not unusual for the callback to be longer than the function you inject it into.

Arrow functions changed that and made writing functions simple and short. And learning about them now will make all the loops you see in future tips much more interesting. It will come as no surprise that arrow functions combined with array methods have led some to abandon for loops altogether.

Well then, what are arrow functions? Arrow functions strip away as much extraneous information as possible.

How much extraneous information is there in a function? Quite a bit. It turns out, you can communicate a function without:

  • The word function

  • Parentheses around arguments

  • The word return

  • Curly braces

All you need to do is use the fat arrow => to indicate that you’ll be building a function. You might be thinking that you’ve just lost everything that makes a function a function. It’s true you can get functions to a minimal state, but there are still a few rules you must follow.

Before you begin, you should know that arrow functions look simple, but they actually have a lot of subtle quirks. Fortunately, you don’t need to understand subtleties now. You’ll get to those when you explore them more in Tip 36, Prevent Context Confusion with Arrow Functions. To start, look at a function that still has most of the extra stuff (parentheses, curly braces, return statements).

Example 1: Function with one parameter

Here’s a simple function that takes an argument and returns a slightly modified value. In this case, it takes a name and returns the name with a capitalized first letter.

Get hands-on with 1200+ tech skills courses.