Arrow Functions

Arrow functions are a cool way to shorten your code. They’re not quite the same as traditional functions. Arrow functions are lexically scoped. We’ll get into that in a moment.

Take our previous array of animals. How would you loop over every animal, and console.log each animal?

Nothing too special, a traditional forEach loop. For each animal, we log out the animal. Let’s refactor our forEach loop to use arrow functions.

Much cleaner and less wordy. The less code we have to write, the less we have to maintain in the future. A good rule of thumb is to write less code, but don’t write overly complicated code.

Here’s a more complex example:

This pattern is called currying. We return a function inside a function. The most notable example that uses currying, would be the connect()() function from Redux.

Note that ** is the exponentiation operator, and it is the equivalent of Math.pow .

The multiplyAndAdd function explained:

multiplyAndAdd takes a number, and returns the base to the exponent power (multiplication).

takes a number, and returns the to the power (multiplication). Adds a number to the exponent.

multiplyAndAdd(2)(4) is the same as 2x2 + 4 .

Let’s write the same functionality using arrow functions.

Less wordy for sure — but we can do even more.

Great, we’re down from six lines to just one line of code!

Caution #1

Notice that there are no return statements. Normally, the return statements are required to return values from functions. Arrow functions call return implicitly, as long as there are no braces. If we use arrow functions with braces, we have to call the return explicitly.

If this is new to you, check out this article about return rules.

Caution #2

The this keyword works differently with arrow functions.

Take this example:

We have a person object. Inside the object, we have two properties; the name of the person, and a function which returns the name of the person .

If we call the sayName method, the first this points to the person object, but the second this is undefined .

Note that the second this actually points to the window object, but since we’re using Quokka, there is no window object.

Second this points to the window

Why does this happen? This is actually a very common interview question as well. Answering this question shows a good understanding of the language mechanics. Check out this StackOverflow answer for an in-depth answer.

Here’s a common workaround for this with regular functions.

Arrow functions are lexically scoped, and its value within the arrow function is determined by the surrounding scope, thus they don’t need this workaround.