Friday, March 27, 2020

Javascript arrow function

JavaScript arrow functions


JavaScript arrow functions are like lambda functions in Python or blocks in Ruby. JavaScript arrow functions are anonymous functions having special syntax. JavaScript arrow functions accept a fixed number of arguments and operate in the function or block of code within which they are defined. The Arrow functions, introduced in ES6 specify a way to write a function concisely (shorter function) in JavaScript. 

So the function written below,

tvar a = function() {
  return "This is normal function";
}

is equivalent to an arrow function,

tvar b = () => {
  return "This is arrow function";
}


Arrow Function Syntax


Basic Syntax to create an arrow function is,


(arg1, arg2, ... argN) => { 

// body of the function

}


A list of arguments within parenthesis (without providing any name to the function and keyword function), followed by a 'fat arrow' (=>), followed by the body of the function. 
 For example,

var search=(arr,element)=>{
    var result='Not found';
    for(i of arr)
    {
      if(i===element)
      {
        result='Found';
        return result;
      }
    }
    return result;
  }


However, there are a number of ways to make an arrow function more concise, like

tconst add = (x, y) => x + y;

OR
tconst getFirst = array => array[0];


Use of "this" in Arrow function


Unlike the normal functions, the value of this inside arrow functions is not dependent on how they are invoked or how they are defined. It depends only on its enclosing context. The "arguments" and "this" both are inherited from the enclosing type in an Arrow function. With an arrow function, this represents the owner of the function.

For example, this is a regular function,


<html>
  <head>
    <title>regular function</title>
   
  </head>
  <body>
    <div id='reg'></div>
  <button id='regbtn'>Test Regular Function</button>
        <script>
    var regFun=function(arg)
    {
      document.getElementById('reg').innerHTML+= this +' '+ arg+'<br>';
    }
  window.addEventListener("load", regFun);
  document.getElementById("regbtn").addEventListener("click", regFun);
    </script>
  </body>
</html>

The result is (after loading the page clicking button 3 times)

For an arrow function,

<html>
  <head>
    <title>regular function</title>
   
  </head>
  <body>
    <div id='arrow'></div>
  <button id='regbtn'>Test Regular Function</button>
        <script>
    var arrowFun=(arg)=>
    {
      document.getElementById('arrow').innerHTML+= this +' '+ arg+'<br>';
    }
  window.addEventListener("load", arrowFun);
  document.getElementById("regbtn").addEventListener("click", arrowFun);
    </script>
  </body>
</html>                 

The result of the same events is,