difference between function and arrow function

Difference between Function and Arrow Function

Functions and Arrow functions are two ways to define functions in JavaScript. Both are used to perform particular actions and return a value. However, there are some differences between the two that are important to understand.

Function

A function is a JavaScript procedure or set of statements that performs a specific task. It is declared with the function keyword, followed by the function name, and then a set of parentheses that may include parameters. The function body is enclosed in curly braces.


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

In the example above, we have defined a function named "add" that takes two arguments and returns their sum.

Functions have a number of advantages over arrow functions. They can be used as constructors, have their own scope, and can be called using the "this" keyword.

Arrow Function

An arrow function is a shorter way to write a function expression in JavaScript. It was introduced in ES6 and has a more concise syntax compared to traditional functions.


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

The above example shows how to define an arrow function named "add" that takes two arguments and returns their sum. Note that there are no curly braces in this example, which means that the return statement is implicit.

Arrow functions are particularly useful when working with callbacks and in situations where we need to preserve the value of "this".

Differences between Function and Arrow Function

  • Function can be used as constructors, while arrow functions cannot.
  • Functions have their own scope, while arrow functions share the scope of their parent.
  • The "this" keyword behaves differently in functions and arrow functions. In functions, "this" refers to the object on which the function is invoked, while in arrow functions, "this" refers to the parent scope.
  • Functions have a more verbose syntax compared to arrow functions, which can make them harder to read and write.

Both functions and arrow functions have their own uses and advantages. It is important to understand the differences between them so that you can choose the right one for your situation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe