top of page
Writer's pictureThe Tech Platform

Arrow Function vs Regular Function in JavaScript

Updated: Jun 1, 2023

JavaScript provides two main ways to define functions: arrow functions and regular functions. Both serve the purpose of executing a block of code, but they have distinct differences in syntax, behavior, and use cases. Understanding these differences is essential for writing clean and efficient JavaScript code. In the article "Arrow Function vs Regular Function in JavaScript", we will explore the differences and examine their syntax, behavior, usage scenarios, and the advantages and disadvantages they bring to the table.

Arrow Function vs Regular Function

Arrow Function

The arrow function is a concise and simplified way of creating functions in JavaScript compared to regular functions.


Arrow functions provide a simpler and clearer syntax for creating functions compared to regular functions. The syntax of an arrow function is as follows:

let myFunction = (arg1, arg2, ...argN) => {
    statement(s);
};

In this syntax:

  • myFunction is the name of the function (optional).

  • arg1, arg2, ...argN are the function arguments (also optional).

  • statement(s) is the body of the function, where you write the code that should be executed.

Here's an example to illustrate the usage of arrow functions:

// Regular function
let multiply = function(x, y) {
    return x * y;
};

// Arrow function
let multiply = (x, y) => x * y;

In this example, the regular function multiply takes two arguments x and y and returns their product using the return statement. The equivalent arrow function multiply achieves the same result with a more concise syntax.


Regular Function

Regular functions created using function declarations or expressions are both constructible and callable. This means that you can use the new keyword with regular functions to create new instances or objects, and you can also invoke them as functions.


On the other hand, arrow functions are only callable and not constructible. This means that arrow functions cannot be used as constructor functions with the new keyword to create new instances or objects.


The Difference: Arrow Function vs Regular Function


1. "this" value

The 'this' value in JavaScript refers to the context in which a function is executed. It represents the object on which a method is being called or the object that is currently being constructed. The value of 'this' can vary depending on how a function is invoked. It allows access to the properties and methods of the current object.


Arrow Function

In arrow functions, the "this" value is different from regular functions in JavaScript. Arrow functions do not define their own execution context. Instead, the "this" value inside an arrow function always equals the "this" value from the outer function.


Example:

const myObject = 
{
    myMethod(items)
    {
        Console.log(this);
        const callback = () =>
        {
            Console.log(this);
        };
        items.forEach(callback);
    }
};

myObject.myMethod([1, 2, 3]);

Regular Function

In regular functions, the "this" value is dynamic and depends on how the function is invoked. When a regular function is called, the "this" value is determined by the context of the function invocation.


Example:

function myFunction()
{
    Console.log(this);
}

myFunction();
// logs global object

2. Implicit return

Implicit return refers to the automatic return of a value from a function without explicitly using the return keyword. In arrow functions, if the function body consists of a single expression, you can omit the curly braces {} and the return keyword. The value of the expression is then implicitly returned as the result of the function.


Arrow Function

If an arrow function contains only one expression, you can omit the function's curly braces, and the expression will be implicitly returned. These are called inline arrow functions.


Example:

const increment = (num) => num + 1;

increment(31); // => 32

The increment() arrow consists of only one expression: num + 1. This expression is implicitly returned by the arrow function without the use of the return keyword.


Regular Function

In regular functions, you explicitly use the return keyword to return a value from the function.


Example:

function myFunction()
{
    return 32;
}

myFunction();  //returns 32


3. Arguments object

The arguments object is a special array-like object available inside functions in JavaScript. It contains the values of the arguments passed to the function at the time of invocation. It can be used to access and manipulate the arguments dynamically, regardless of the number of declared parameters in the function signature.


Arrow Function

Arrow functions do not have their own arguments keyword. Instead, they access the arguments object from the outer function.


Example:

function myRegularFunction() 
{
  const myArrowFunction = () => 
  {
    console.log(arguments);
  }

  myArrowFunction('c', 'd');
}

myRegularFunction('a', 'b'); // logs { 0: 'a', 1: 'b', length: 2 }

The arrow function myArrowFunction() is invoked with the arguments 'c', 'd'. Still, inside of its body, arguments object equals to the arguments of myRegularFunction() invocation: 'a', 'b'.


Regular Function

Regular functions have their own arguments object, which is a special array-like object containing the arguments with which the function has been invoked.


Example:

function myFunction() {
  console.log(arguments);
}

myFunction('a', 'b'); // logs { 0: 'a', 1: 'b', length: 2 }

4. Constructors

Constructors are special functions used to create new instances or objects based on a blueprint called a class or constructor function. In JavaScript, constructor functions are typically written with an initial uppercase letter and are invoked using the new keyword. They initialize the newly created object with properties and methods defined within the constructor function.


Arrow Function

Arrow functions cannot be used as constructors. If you try to use an arrow function as a constructor, JavaScript will throw a TypeError.


Example:

const Car = (color) => 
{
  this.color = color;
};

const redCar = new Car('red');

Regular Function

Regular functions can be used as constructors to create new instances of objects.


Example:

function Car(color)
{
    this.color = color;
}

const redCar = new Car ('red');
redCar instanceof Car;

5. Methods

Methods are functions that are associated with objects or classes. They can be accessed and invoked on an object using dot notation or as static methods on a class. Methods perform actions or operations related to the object they belong to and often manipulate the object's properties.


Arrow Function

You can use arrow functions as methods inside classes. Arrow functions used as methods bind the lexical to the class instance, which means this refers to the instance itself.


Example:

class Hero 
{
  constructor(heroName) 
  {
    this.heroName = heroName;
  }

  logName = () => 
  {
    console.log(this.heroName);
  }
}

const batman = new Hero('Batman');

Now, you can use batman.logName as a callback without any manual binding of this. The value of this inside logName() method is always the class instance:

setTimeout(batman.logName, 1000);
// after 1 second logs "Batman"

Regular Function

Regular functions are the usual way to define methods on classes. When using regular functions as methods, you need to be careful with the value of this, especially when passing the method as a callback.


Example:

class Hero 
{
  constructor(heroName) 
  {  
    this.heroName = heroName;
  }

  logName() 
  {
    console.log(this.heroName);
  }
}

const batman = new Hero('Batman');

Sometimes you'd need to supply the method as a callback, for example to setTimeout() or an event listener. In such cases, you might encounter difficulties accessing this value.


For example, let's use use logName() method as a callback to setTimeout():

setTimeout(batman.logName, 1000);
// after 1 second logs "undefined"

6️. Function Hoisting

Function hoisting is a behavior in JavaScript where function declarations and variable declarations are moved to the top of their respective scopes during the compilation phase. This means that you can call or invoke a function before its actual declaration in the code, and JavaScript will still be able to find and execute it. However, it's important to note that only function declarations are hoisted, not function expressions or arrow functions.


Arrow Function

Arrow functions are not hoisted, meaning you cannot access them before they are defined. If you try to call an arrow function before its initialization, you'll get a ReferenceError.


Example:

arrowFunc()const arrowFunc = () => {
    return "Arrow Function"
}// ReferenceError: Cannot access 'arrowFunc' before initialization 

Regular Function

Regular functions are hoisted to the top of their scope, so you can call them before their actual definition.


Example:

normalFunc()function normalFunc() 
{
    return "Normal Function"
}// "Normal Function"

Conclusion

Both arrow functions and regular functions have their own use cases and advantages. Arrow functions provide concise syntax, lexically bind this, and are suitable for use in functional programming paradigms. Regular functions offer more flexibility, support the new keyword for object instantiation, and have access to their own arguments object.

0 comments

Kommentare


bottom of page