Difference Between Regular Functions and Arrow Functions

Difference Between Regular Functions and Arrow Functions

What are Regular Functions and Arrow Functions?

Regular Function

A regular function (function expression) is a traditional way to write functions. (Check out my other blog post to learn more about function declarations and functions expression!)

  const addNums = function (a, b) {
    return a + b;
  };

  console.log(addNums(5, 6)); //11

Arrow Function

An arrow function is a new way to write functions in ES6, a compact alternative to a traditional function expression. There are 2 ways of writing it - with or without curly braces. If you have additional lines inside the function, you would need to use the curly braces and add return.

  const addNums1 = (a, b) => {
    return a + b;
  };

  const addNums2 = (a, b) => a + b;

  console.log(addNums1(5, 6)); //11
  console.log(addNums2(5, 6)); //11

Limitations of Arrow Functions

1. Not Suitable to be used as methods

Arrow functions are not suitable to be used as methods. Use regular functions instead for methods.

  const obj = {
    i: 10,
    b: function () {
      console.log(this.i, this);
    },
    c: () => console.log(this.i, this), //not suitable
  };

2. Don't have their own bindings to this, arguments or super

Another limitation is that the arrow functions do not have their own bindings to this, arguments, or super. This is another reason why the example above does not work.

  const obj = {
    i: 10,
    b: function () {
      console.log(this.i, this);
    },
    c: () => console.log(this.i, this),
  };

  //using regular functions
  obj.b(); // 10 {i: 10, b: ƒ b(), c: ƒ c()}

  //using arrow functions
  obj.c(); // TypeError: Cannot read properties of undefined (reading 'i')

3. Not suitable for "call", "apply" and "bind" methods

Arrow functions establish this based on the scope the arrow function is defined within. Therefore, arrow functions are not suitable to use with call, apply, and bind. Check out this great example on the MDN Docs to understand better!

Reference

MDN Docs Arrow function expressions

5 Differences Between Arrow and Regular Functions

What are the differences between arrow functions and regular functions in JavaScript?

Arrow functions vs regular functions in JavaScript