Regular functions vs Arrow functions in JavaScript?

Front End TechnologyJavascriptObject Oriented Programming

Regular functions vs Arrow functions

An arrow function is used to write the code concisely. Both functions regular and arrow work in a similar manner but there are some differences between them. Let's discuss those differences in a nutshell.

syntax of an arrow function

let x = (params) => {
// code
};

syntax of a regular function

let x = function functionname(params){
// code
};

Usage of "this" keyword

It is unable to use "this" keyword in arrow functions whereas in regular functions it can be used without any disturbance.

Example

In the following example, both regular(rectangle) and arrow(square) functions were used inside the object "num", which consists of len(length) and bre(breadth) properties. Our aim is to find the area of the square(len*len) using arrow function and area of the rectangle(len*bre) using the regular function. But since "this" keyword doesn't work in an arrow function the value of the area of the square is returned as "NaN" whereas using the regular function we got an exact area of the rectangle as shown in the output.

Live Demo

<html>
<body>
<script>
   var num = {
      len: 12,
      bre: 13,
      square:() => {
         document.write(this.len * this.len);
      },
      rectangle(){
         document.write(this.len * this.bre);
      }
   };
   num.square();
   document.write("</br>");
   num.rectangle();
</script>
</body>
</html>

Output

NaN
156


Usage of 'new' keyword 

The arrow functions are not "constructible" but "callable" so the keyword "new" doesn't work here whereas the regular functions are both "callable" and "constructible" therefore "new" keyword works here. 

Example

In the following example, Using "new" keyword some arguments have been passed to both the regular and arrow function. But since the arrow function is not "constructible" we will get an error whereas we will get a legitimate output to the regular functions.

<html>
<body>
<script>
   var word = function(){
      document.write(JSON.stringify(arguments)); 
       ///  executes '{"0":"Tutorix","1":"Tutorialspoint"}' as output
   };
   new word("Tutorix","Tutorialspoint");  
   var newword = ()=> {
      document.write(JSON.stringify(arguments)); 
      //executes 'newword is not a constructor' as output
   };
   new newword("Tutorix","Tutorialspoint");
</script>
</body>
</html>
raja
Published on 26-Aug-2019 15:49:36
Advertisements