Menü schliessen
Created: September 3rd 2021
Last updated: December 10th 2021
Categories: Common Web Development,  JavaScript Development
Author: Tim Fürer

JavaScript: Arrow Functions And How to Use Them

Tags:  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In this guide, we'll talk about arrow functions. They allow you to write super-short and concise functions!

Defining an Arrow Function And Shortening It

This is a normal function:

const myFunction = function(name) {
	return 'Hello, my name is ' + name;
}

This is the same as above, but written as an arrow function:

const myFunction = (name) => {
	return 'Hello, my name is ' + name;
}

As you can see, we've left out 'function' before the parentheses, but have added an arrow (=>) between them and the curly brackets.

We can write shorter. Arrow functions allow us to omit the 'return', because they'll assume you mean to return when only bare values are given:

const myFunction = (name) => {
	'Hello, my name is ' + name;
}

There's still more. If you only have to pass a single parameter, in this case 'name', you're allowed to leave out the parentheses, too:

const myFunction = name => {
	'Hello, my name is ' + name;
}

And if you keep the whole thing on one line, you may remove the curly brackets also:

const myFunction = name => 'Hello, my name is ' + name;

The result? Nice and short, straight to the point code. Cool, huh?

'This' is Different For Arrow Functions (IMPORTANT!)

Yes, with arrow functions, 'this' works differently. Unlike how 'this' inside traditional functions will refer to the caller of the function, 'this' inside arrow functions will always refer to the object that has defined the arrow function.

References

W3, JavaScript Arrow Function