Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 17, 2021 10:14 am GMT

The Arrow Function in JS!

Hey fellow creators

The arrow function exists since 2015 and is quite different from the classic functions. Lets 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;

Its 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.


Original Link: https://dev.to/ziratsu/the-arrow-function-in-js-528f

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To