DEV Community

Cover image for Arrow Functions
Shreyas Pahune
Shreyas Pahune

Posted on • Edited on

Arrow Functions

Hey everyone 👋🏻, in this blog we are going to discuss about :

  • Arrow Functions V/S Regular Functions
  • Advantages and Disadvantages of using Arrow Functions

Like I said in my previous blog, the arrow function is not a new concept, it is just a syntax revamp of the regular function in JS. The new syntax is very very easy, it is just a sugar coating around the old function syntax so without wasting anymore time let's start learning about arrow functions!

1. Arrow Functions V/S Regular Functions

We are going to discuss 4 different types of functions and we'll transform them from the old rusty ES5 syntax to ES6 syntax.

4 different types are going to be:

  1. A named function with no parameters.
  2. A named function with one parameter.
  3. A named function with two parameters.
  4. An unnamed function.

1. Named function with no parameters :
nameFunctionNoParam

As you can see in the above photo, we have to give the name of the function as a variable name and after an equal symbol = an opening and closing parenthesis ( ) which will denote the function, leading with an arrow => which is nothing but an equal sign and angular bracket.

There is another way of making an one liner arrow function, you just have to give the function name as a variable name and = sign leading with => arrow and the statement you want to return.

2. Named function with one parameter :
nameFunctionOneParam

There is no change except in the parenthesis ( ) in which we will pass our parameters.

3. Named function with two parameters :
nameFunctionTwoParam

4. Unnamed function :
unamedFunction



Isn't this cool??

2. Advantages and Disadvantages of using Arrow Functions

Arrow functions make our code more concise and increases the readability of the code, the new syntax is really easy to adopt and takes no time to understand things.

Apart from writing less and doing more Arrow Function can help us with this keyword and scoping of variables, let me show you how.

classThis

Here in this above image I have made a class with 2 member functions, arrow and regular which consists of setTimeout to make a block of code so that we can see the scope of this keyword using arrow functions v/s regular function.

Here we will receive the name(Shreyas) and age(18) in the arrow function, as inside this function this keyword will use the scope where it was created ( i.e. inside the class ) but on the other hand the regular function will use the scope where it is invoked or called i.e. which is outside the class and since there is no name and age defined outside the class, we will receive undefined.

One disadvantage I feel is, we can not use arrow function to define constructor.

A constructor is a special function which is to be made inside every class, which basically sets default values and initializes them.

In the above example you can see I have made a constructor function, but with normal function's syntax.


Thank you so much for reading the whole blog 🎉! I hope you learnt something and if you did, do implement it, it would make your code more concise and readable.

Top comments (3)

Collapse
 
peerreynders profile image
peerreynders • Edited

One disadvantage I feel is, we can not use arrow function to define constructor.

There are other disadvantages:

  • class methods are shared via the prototype object so there is only one function value per method per class.
  • arrow functions are function values bound to an instance field - so there is a function value dedicated to each object created by the class. This has implications if you plan to use inheritance.
class A {
  myArrow = () => {
    console.log('A.myArrow()');
  }

  myMethod() {
    console.log('A.myMethod()');
  }
}

class B extends A {
  myArrow = () => {
    super.myArrow(); // arrow function exists on 
                     // public class field of A but
                     // but is not available on 
                     // the prototype chain via `super`
    console.log('B.myArrow()');
  }

  myMix() {
    super.myArrow(); // same problem
    console.log('B.myMix()');
  }

  myMethod() {
    super.myMethod(); // just works
    console.log('B.myMethod()');
  }
} 

let myB = new B();

myB.myMethod(); // 'A.myMethod()'
                // 'B.myMethod()'
myB.myMix();    // Uncaught TypeError: (intermediate value).myArrow is not a function at B.myMix
myB.myArrow();  // Uncaught TypeError: (intermediate value).myArrow is not a function at B.myArrow
Enter fullscreen mode Exit fullscreen mode

So only use arrow functions in classes when there is a very good reason to (i.e. to avoid having to use bind anyway).

Classes often use arrow functions as reusable event listeners. However EventTarget.addEventListener() can also accept objects as listeners as long as they implement EventListener.handleEvent().

React's synthetic event system doesn't support object event listeners however object event listeners can be used via useEffect().


Technically arrow functions cannot be named.

const randomize = () => Math.random();
Enter fullscreen mode Exit fullscreen mode

All that is happening here is that an anonymous function expression is bound to a variable name. To get a named function expression:

const randomize = function randomize() {
  return Math.random();
};
Enter fullscreen mode Exit fullscreen mode

What is the difference?
In the following the locally available function name fibRec is used:

const fn = function fibRec(n2, n1, i) {
  const next = n2 + n1;
  return i > 1 ? fibRec(n1, next, i - 1) : next;
}

const fib = function(n) {
  return n > 1 ? fn(0, 1, n - 1) : n > 0 ? 1 : 0;
}

console.log(fib(20)); // 6765
Enter fullscreen mode Exit fullscreen mode

With arrow functions the variable name fn from the creating scope has to be used:

const fn = (n2, n1, i) => i > 1 ? fn(n1, n2 + n1, i - 1) : n2 + n1;

const fib = (n) => n > 1 ? fn(0, 1, n - 1) : n > 0 ? 1 : 0;

console.log(fib(20)); // 6765
Enter fullscreen mode Exit fullscreen mode

Contrast this with a function declaration which cannot be unnamed.

function randomize() {
  return Math.random();
};
Enter fullscreen mode Exit fullscreen mode

The advantage of a function declaration is that it is hoisted to the top of the scope. This works:

const SOME_CONSTANT = 2 * Math.PI;

console.log(calculate(10)); // 62.83185307179586

function calculate(radius) {
  return SOME_CONSTANT * radius;
}
Enter fullscreen mode Exit fullscreen mode

This does not work:

const SOME_CONSTANT = 2 * Math.PI;

console.log(calculate(10)); // Uncaught ReferenceError: Cannot access 'calculate' before initialization

const calculate = (radius) => SOME_CONSTANT * radius;
Enter fullscreen mode Exit fullscreen mode

This doesn't work either:

const SOME_CONSTANT = 2 * Math.PI;

console.log(calculate(10)); // TypeError: calculate is not a function

var calculate = (radius) => SOME_CONSTANT * radius;
Enter fullscreen mode Exit fullscreen mode

While var calculate is hoisted, the assignment isn't.

Collapse
 
aathishithan profile image
Aathishithan G

As vice versa, we cant achieve call, apply with arrow function.

Collapse
 
shreyazz profile image
Shreyas Pahune

Yup, that's true!