Functions: Arrow functions

Arrow functions are very often used instead of “regular” functions, the one I described in the previous chapter. You’ll find both forms used everywhere.

Visually, they allows you to write functions with a shorter syntax, from:

function test() {
  //...
}

to

() => {
  //...
}

But.. notice that we don’t have a name here.

Arrow functions are anonymous. We must assign them to a variable.

We can assign a regular function to a variable, like this:

let test = function test() {
  //...
}

When we do so, we can remove the name from the function:

let test = function() {
  //...
}

and invoke the function using the variable name:

let test = function() {
  //...
}
test()

Although it’s generally recommended to avoid so, for one simple reason: when you have errors, naming your functions helps JavaScript give you back helpful error messages, so you can fix your bugs quicker.

That’s the same thing we do with arrow functions:

let test = () => {
  //...
}
test()

If the function body contains just a single statement, you can omit the parentheses and write all on a single line:

const test = () => console.log('hi!')

Parameters are passed in the parentheses:

const test = (param1, param2) => console.log(param1, param2)

If you have one (and just one) parameter, you could omit the parentheses completely:

const test = param => console.log(param)

Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword.

It works when there is a on-line statement in the function body:

const test = () => 'test'

test() //'test'

Like with regular functions, we can have default parameters, in case they are not passed:

const test = (color = 'black', age = 2) => {
  //do something
}

And as with regular functions, we can only return one value.

The are very similar to regular functions. The big difference with regular functions is when they are used as object methods and their relation to the this keyword, which is something we’ll soon look into.

Lessons in this unit:

0: Introduction
1: Function parameters
2: Returning values from a function
3: ▶︎ Arrow functions
4: Nesting functions
5: Immediately-invoked functions
6: Recursive functions
Want to learn more? Check out our courses