Arrow Functions

mbilgil profile image Mehmet Bilgil ・2 min read

Alt text of image

In this article, we will see how to use another important feature of JavaScript which is Arrow Functions.

Regular Function Syntax

Arrow Function Syntax

Difference Between Regular Function and Arrow Function

The value of this keyword inside Regular function depends on how that function was called (The object that made a call)

The value of this keyword inside Arrow function depends on where the function was defined (the scope that defined the function)

Regular Function gives access to its ‘calling‘ environment.

Arrow Function gives access to its ‘defining‘ environment.

Let’s understand this with an example;

We have defined two functions inside the const variable CallerObj. First one (func1) is Regular function and Second (func2) is Arrow function.

When you call both functions and see results in the console window of browser you see that func1’s this keyword value is associated with the calling object (CallerObj).

and, func2’s this keyword value is associated with the window object.

So, the conclusion is that in the Arrow function value of this doesn’t decide on who is calling it. It is decided at the time of definition of this.

Here are the results of the above code;
Alt text of image

Single Line Function

An arrow function is useful where a function has a single line of code. For example, a function is returning some value.

Let’s look at examples,

1-Below is the Arrow function which returns multiplication values.
2-You can write this function in one line.

Example of map function which takes arrow function as a parameter.

There are several other uses of arrow functions but for learning React above points mentioned about Arrow functions are enough. If you want to go deeper then you can learn here more about them.


markdown guide