JavaScript arrow function vs function | Difference

  • by

JavaScript arrow function and function work in a similar manner, there are certain differences between them. Syntax difference between arrow function vs function in JavaScript.

Syntax of regular functions:-

let x = function function_name(parameters){
   // body of the function
};

Syntax of arrow functions

let x = (parameters) => {
    // body of the function
};
  • Unlike regular functions, arrow functions do not have their own this.
  • Arguments objects are not available in arrow functions, but are available in regular functions.
  • Regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible.

Example arrow function vs normal function in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    //Regular function
    let squar = function(x){
      return (x*x);
    };
    console.log("Regular",squar(9));

    //Arrow function
    var square = (x) => {
      return (x*x);
    };
    console.log("Arrow",square(100));
  </script>

</body>
</html> 

Output:

JavaScript arrow function vs function

Use of this keyword

<script>
    let user = {
      name: "Hello",
      f1:() => {
        console.log("World " + this.name); // no 'this' binding here
      },
      f2(){       
        console.log("Welcome to " + this.name); // 'this' binding works here
      }  
    };
    user.f1();
    user.f2();
</script>

Output: World

Welcome to Hello

Availability of arguments objects

Regular function

let user = {      
    show(){
        console.log(arguments);
    }
};
user.show(1, 2, 3);

Arrow function

let user = {     
        show_ar : () => {
        console.log(...arguments);
    }
};
user.show_ar(1, 2, 3);

Using new keyword

Regular function

let x = function(){
    console.log(arguments);
};
new x =(1,2,3);

Arrow function

let x = ()=> {
    console.log(arguments);
};
new x(1,2,3);

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.