Sobes.tech
Junior

What is the difference between arrow functions and regular functions in JavaScript?

sobes.tech AI

Answer from AI

  1. Syntax:
    • Regular function: function myFunction() { ... }
    • Arrow function: () => { ... } or param => { ... }
  2. this context:
    • Regular function: this is determined by the call context.
    • Arrow function: this is lexically inherited from the surrounding scope (does not have its own this).
  3. Constructors:
    • Regular function: Can be used as a constructor (new myFunction()).
    • Arrow function: Cannot be used as a constructor.
  4. arguments object:
    • Regular function: Has its own arguments object containing passed arguments.
    • Arrow function: Does not have its own arguments object; access to arguments is through rest parameters (...args).
  5. Named functions:
    • Regular function: Can be named (function myFunction() { ... }).
    • Arrow function: Anonymous by default, assigned to a variable for naming (const myFunction = () => { ... }).
  6. Implicit return:
    • Regular function: Requires explicit return to return a value (except for simple cases like IIFE).
    • Arrow function: Can implicitly return the result of an expression in a single-line body.

Comparison table:

Characteristic Regular function Arrow function
Syntax function name() { ... } () => { ... }
this context Dynamic (call context) Lexical (from parent scope)
Constructor Yes No
arguments object Yes No (uses rest parameters)
Naming Can be named Anonymous (assigned)
Implicit return No (usually requires return) Yes (for single-line body)
// Examples of regular functions
function standardFunction() {
  console.log(this); // Depends on call context
  console.log(arguments); // `arguments` object is available
}

const obj = {
  method: standardFunction
};

standardFunction(); // `this` will be window (browser) or undefined (strict mode)
obj.method(); // `this` will be obj
new standardFunction(); // `this` will be a new instance of standardFunction

// Examples of arrow functions
const arrowFunction = () => {
  console.log(this); // Inherits `this` from parent scope (e.g., Global or module)
  // console.log(arguments); // Error, `arguments` is not accessible
};

const outerObj = {
  outerMethod: function() {
    const innerArrowFunction = () => {
      console.log(this); // Inherits `this` from outerMethod (which is outerObj)
    };
    innerArrowFunction();
  }
};

arrowFunction(); // `this` will be window (browser) or {} (Node.js)
outerObj.outerMethod(); // `this` inside innerArrowFunction will be outerObj

// Implicit return in arrow function
const sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5 (implicit return of `a + b`)

// Regular function with explicit return
function multiply(a, b) {
  return a * b;
}
console.log(multiply(2, 3)); // 6

// Arrow function cannot be a constructor
// new arrowFunction(); // Error: TypeError: arrowFunction is not a constructor