Hey fellow creators
The arrow function exists since 2015 and is quite different from the classic functions. Let’s see how !
If you prefer to watch the video version, it's right here :
1. How to use an arrow function.
Here is the basic syntax, we don't need the "function" keyword and we put it by default in a constant, that way we won't have hoisting issues.
const add = (a,b) => {
return a + b;
}
console.log(add(2,2));
If you have just a return, you can use the short version.
const add = (a,b) => a + b;
If you have one parameter (but only one), you can remove the parenthesis which would make it even more concise:
const add = a => a;
It’s very useful when you use it with some higher order function like the map.() method:
const multiplied = array.map(num => num * 2)
2. The difference between a classic function and an arrow function.
The main difference between the classic and arrow function is the value of "this".
If you use a classic function as the value of a property in an object, "this" will refer to the calling context, i.e. the obj where the function is defined :
const obj = {
a: 5,
foo: function() {
console.log(this)
}
}
obj.foo() // {a: 5, foo: ƒ}
Otherwise, if you use an arrow function, "this" will return the global object.
const obj = {
a: 5,
foo: () => {
console.log(this)
}
}
obj.foo() // Window Object
In that case, this will refer to the parent of the calling context, thus the global object.
Instead of refering the direct context, it will refer to the parent of that context.
You need to keep that difference in mind when you are dealing with functions and the "this" keyword.
Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool
Enzo.
Top comments (3)
I would write this, 'cause methods rarely ever benefit from arrows anyway:
Agreed, I'd rather do it like that.
Agreed too, but I think that the function keyword is more comprehensible for a beginner, that's why I've used it there.
But in a real workflow the shorter version is better.