Explain arrow functions and their differences from regular functions. When should you use each?

3 minintermediatejavascriptes6arrowfunctionsdifferencesregular

Quick Answer

Arrow functions are a concise syntax for writing function expressions in ES6.

Detailed Answer

Explain arrow functions and their differences from regular functions. When should you use each?

Arrow functions are a concise syntax for writing function expressions in ES6. Here are the key differences:

Syntax Differences:

// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

// Multiple parameters
const multiply = (a, b) => {
  return a * b;
};

// Single parameter (parentheses optional)
const square = x => x * x;

// No parameters
const getTime = () => new Date();

Key Differences:

  1. this Binding:
const obj = {
  name: 'John',
  regularFunction: function() {
    console.log(this.name); // 'John' - this refers to obj
  },
  arrowFunction: () => {
    console.log(this.name); // undefined - this refers to global/window
  }
};

obj.regularFunction(); // 'John'
obj.arrowFunction(); // undefined
  1. Arguments Object:
function regularFunction() {
  console.log(arguments); // Has arguments object
}

const arrowFunction = () => {
  console.log(arguments); // ReferenceError: arguments is not defined
};
  1. Constructor Usage:
function RegularConstructor() {
  this.name = 'test';
}

const ArrowConstructor = () => {
  this.name = 'test';
};

new RegularConstructor(); // Works
new ArrowConstructor(); // TypeError: ArrowConstructor is not a constructor
  1. Hoisting:
// Regular functions are hoisted
console.log(regularFunc()); // Works - 'Hello'

function regularFunc() {
  return 'Hello';
}

// Arrow functions are not hoisted
console.log(arrowFunc()); // ReferenceError: Cannot access 'arrowFunc' before initialization

const arrowFunc = () => 'Hello';

When to Use Each:

Use Arrow Functions When:

  • Writing short, simple functions
  • Working with array methods (map, filter, reduce)
  • Need lexical this binding
  • Writing functional programming style code
// Great for array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

Use Regular Functions When:

  • Need this to be dynamically bound
  • Need access to arguments object
  • Creating constructors
  • Need function hoisting
  • Writing methods in objects/classes
// Object methods should use regular functions
const calculator = {
  value: 0,
  add: function(num) {
    this.value += num;
    return this;
  },
  multiply: function(num) {
    this.value *= num;
    return this;
  }
};