Could we help you? Please click the banners. We are young and desperately need the money
In this guide, we'll talk about arrow functions. They allow you to write super-short and concise functions!
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?
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.