JavaScript Arrow Functions

Arrow function was introduced with ES6 as a new syntax for writing JavaScript functions. There are a few differences between arrow functions and regular functions

Arrow Function vs Regular Function
Arrow Function Regular Function
The value of this will always be inherited from the outer function. If there is no outer function, this will refer to the global object. In other words, the arrow function resolves this lexically. The value of this depends how the function is invoked or who owns the function:
  • 1. Simple invocation - this refers to the global object
  • 2. Method invocation – this refers to the parent object
  • 3. Constructor invocation – this refers to the newly created instance
Doesn’t have arguments object but we can access the arguments using a rest parameter …args Has a special arguments object containing the list of arguments
Supports implicit return expression statement. return expression statement needs to be explicitly declared.
A class method defined as arrow function will always bind this to the class instance. If a class method defined as a regular function and used as a callback, we have to bind this to the method.

Arrow Functions should be used when
  • The value of this needs to be consistent and returns the same value always
  • The function has only one line of statement and which may be a simple return expression
  • The function doesn't need to access its arguments object
  • Callback functions with static context
Arrow Functions shouldn't be used when
  • As an object property or object prototype (this inside the arrow function will refer to "window" object instead of the parent object/function)
  • Callback functions with dynamic context
  • The function will be used as a constructor
  • The return expression statement needs to be explicit
  • Need to access the arguments object of the function

Share this post

MeghSohor

Follow me on Social Media