Skip to content

JavaScript arrow function vs function | Difference

  • by

JavaScript arrow function and function work in a similar manner, but there are specific 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 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);

Here’s a comparison of JavaScript function declarations and arrow functions in a tabular format:

FeatureFunction DeclarationArrow Function
Syntaxfunction name(parameters)(parameters) => expression
HoistingYesNo
Named/AnonymousCan be bothAlways anonymous
this BehaviorOwn this contextLexical this context
ConstructorYesNo
Use CasesMethods, Constructors, etc.Short, one-liner functions, Callbacks in array methods

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. Required fields are marked *