Modern JavaScript for React: Arrow Functions – Part 2

In the last article, we have seen how to use Variables and Block Scope in modern JavaScript.

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

Regular Function Syntex

 
  const abc = function () {
                     
  }
 

Arrow Function Syntex

 
 const abc = () => {
                     
  }
 

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,

 
  const CallerObj = {
       func1: function () {
        console.log('function1', this);
       },           
       func2: () => {
        console.log('function2', this);
       },        
   };
   CallerObj.func1();
   CallerObj.func2();
 

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,

Arrow Functions Javascript

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,

Below is the Arrow function which returns multiplication values.

 
  const result = (a) => {
     return a * a;
  };
 

You can write this function in one line.

 
  const result = (a) => a * a
 

If a function has only one parameter like above then you can remove parentheses also.

 
  const result = a => a * a
 

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

 
 [10, 11, 12, 14].map(a => a * a)
 

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.

In upcoming articles, we will be looking more into Modern JavaScript part required to Learn React js.


Subscribe Now!

Subscribe Us For Latest Articles