Since you already know how to use Named functions
and Anonymous functions
let me show
you another type of function which you will be dealing with while building Angular Applications
Let's have a look at the following sample:
You can write the same using arrow functions
(sometimes also called fat arrow
functions):
As you can see they are not that fat :) They are actually, shorter and less verbose than traditional function expressions. Arrow functions have two huge advantages, the first one you already know:
1. Shorter syntax:
Arrow functions are always anonymous and turn:
into:
In the case that your function doesn't use any input parameters, you can use even shorter syntax:
When you only have one parameter, the opening parentheses are optional:
Finally, if you are returning an expression, you can remove the brackets and return statement:
2. Handling `this`
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
Arrow functions do not have
Consider the following example:
As you can see, when we are using normal functions this
corresponds to the name: john
(the closest object), while in case of arrow function, this refers to the global scope: david
Why is it important?
Functions always have their own this
. But that prevents you from accessing the this
of,
e.g., a surrounding method from inside a callback:
This will generate an error:
This is because, in line C, we’d like to access this.prefix, but can’t, because the this
of the
function from line B shadows the this
of the method from line A. In strict mode, this is undefined
in non-method functions, which is why we get an error if we use Prefixer.
There is a workaround which we can use:
But this is tricky and makes code more complex, while using an arrow function solves the issue:
Lesson summary:
Since ES6, you can use arrow functions to make your code less verbose:
As a disclaimer, there is more to arrow functions than what was explained in this article. But this should give you a great base for further learning! As always, leave a comment if you have any great resources on the subject for others to explore.