This content originally appeared on DEV Community and was authored by Ustariz Enzo
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/Learntocreate/videos
Enzo.
This content originally appeared on DEV Community and was authored by Ustariz Enzo
Ustariz Enzo | Sciencx (2021-12-17T10:14:06+00:00) The Arrow Function in JS!. Retrieved from https://www.scien.cx/2021/12/17/the-arrow-function-in-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.