DEV Community

Raja71
Raja71

Posted on

Difference Between Regular Functions and Arrow Functions

“What is the difference between regular functions and arrow functions?” is one of the most commonly asked JavaScript interview questions.

While both look similar, they behave very differently when it comes to this, arguments, constructors, and more. In this blog, we’ll understand these differences with easy examples and real-world scenarios.

Regular Functions

  1. Syntax

Regular functions must use the function keyword.

const add = function (num1, num2) {
return num1 + num2;
};

  1. arguments object

Regular functions automatically get a special object called arguments.

You can access all passed values even without parameters.

const add = function () {
console.log(arguments);
};

add(1, 2, 3, 4);

Output:

{0: 1, 1: 2, 2: 3, 3: 4}

  1. No implicit return

Regular functions do NOT return values automatically.

You must explicitly use return.

const sum = function (a, b) {
a + b; // nothing returned
};

  1. this keyword

In regular functions, this depends on how the function is called.

let learnLng = {
lang: "JavaScript",
learnLang: function () {
console.log("Will start learning", this.lang);
}
};

learnLng.learnLang();
// Will start learning JavaScript

Arrow Functions

  1. Syntax (short & clean)

Arrow functions are more concise.

const multiply = (num1, num2) => num1 * num2;

  1. No arguments object

Arrow functions do NOT have their own arguments.

const add = () => {
console.log(arguments);
};

add(1, 2, 3);

ReferenceError: arguments is not defined

If you need arguments in arrow functions, use rest parameters:

const add = (...args) => {
console.log(args);
};

  1. Implicit return

If the function has only one statement, arrow functions return it automatically.

const square = x => x * x;

No return needed

  1. this keyword (lexical)

Arrow functions do NOT have their own this.

Instead, they borrow this from where they are written, not from how they are called.

let learnLng = {
lang: "JavaScript",
learnLang1: () => {
console.log("Will start learning", this.lang);
},
learnLang2: function () {
console.log("Will start learning", this.lang);
}
};

learnLng.learnLang1(); // undefined
learnLng.learnLang2(); // JavaScript

Why does this happen?
learnLang1 (arrow function):

this comes from outer scope

NOT from learnLng

So this.lang is undefined

learnLang2 (regular function):

this points to the object calling it (learnLng)

TL;DR

  • Regular functions use the function keyword; arrow functions use =>
  • Regular functions have their own this; arrow functions inherit this
  • Regular functions support arguments; arrow functions do not
  • Arrow functions allow implicit return for single expressions
  • Arrow functions cannot be used as constructors
  • Use regular functions for object methods
  • Use arrow functions for callbacks and short functions

Top comments (0)