DEV Community

Cover image for The Arrow Function in JS!
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

The Arrow Function in JS!

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));

Enter fullscreen mode Exit fullscreen mode

If you have just a return, you can use the short version.

const add = (a,b) => a + b;
Enter fullscreen mode Exit fullscreen mode

If you have one parameter (but only one), you can remove the parenthesis which would make it even more concise:

const add = a => a;
Enter fullscreen mode Exit fullscreen mode

It’s very useful when you use it with some higher order function like the map.() method:

const multiplied = array.map(num => num * 2)
Enter fullscreen mode Exit fullscreen mode

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: ƒ}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
webreflection profile image
Andrea Giammarchi

I would write this, 'cause methods rarely ever benefit from arrows anyway:

const obj = {
    a: 5,
    foo() {
        console.log(this)
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shrihankp profile image
Shrihan

Agreed, I'd rather do it like that.

Collapse
 
ziratsu profile image
Ustariz Enzo

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.