Arrow functions in JavaScript

Like functions, but shorter…more or less. Let’s find out!

Lorenzo Felletti
2 min readJan 9, 2021
Photo by Steinar Engeland on Unsplash

Arrow functions are those weird functions using a funny syntax mimicking how humans write or draw them on paper:

(param1, param2) => { /* do something */ }

Are they just a shorter way to write function, or is there more?

The answer is yes, they’re mostly a shorter way to write functions, but there are some little differences.

Arrow functions are anonymous

The first thing you may note from the above snippet is that arrow functions haven’t got a name — they’re anonymous.

For instance, you cannot write something like this:

functionName(param) => { /* do smth */ }

But you can get around this “problem” by assigning it to a variable, which is always possible because functions are first-class citizens in JavaScript.

Arrow function example

In the above example, we created an adder called add using an arrow function.

In the above example, we omitted the brackets and the return statement. This isn’t an error, in fact when the function is just one instruction you can omit them. Also, if the function has only one input param you can avoid the parenthesis.

Arrow functions haven’t got a scope

Arrow functions don’t have their own bindings this or super. Thus, arrow functions can't be used as constructors.

It is important to remember that this used inside an arrow function reference this from their outer function/scope.

Common use case

Callback functions are usually defined as arrow functions because of the simpler syntax.

setTimeout(() => console.log("Hello World"), 3000)

The above example set a 3 seconds timeout at the end of which it will display “Hello World”. In this example, defining the callback function as a regular or arrow one makes no difference in terms of the output, with the latter to be preferable because is shorter to write and — in my humble opinion — easier to read.

Anyway, the small differences between regular and arrow functions must be known to avoid unexpected behavior by the code we write.

--

--