Monday, May 11, 2020

arrow functions v/s normal functions


Arrow functions were introduced with ES6, also called the FAT Arrow functions.

Lets point out some differences between these 2 types of functions.


1. Syntax wise arrow functions look pretty short and sweet

 so one would think of using them every single time instead of a normal function. But, this cannot be true every time since the scope of arrow functions works differently.


Arrow Function
a() => {}

Normal function
function a() {
}


2. Scope of this in arrow functions.


Arrow functions take the 'this' using lexical scoping from its parents, whereas normal function have the current function used as 'this'.
Eg:


  • Function inside a function case.

function normal() { this.localVar = 10; normalinner = function() { console.log("printing localVar", this.localVar) // 10, as 'this' points to normalinner function. But it is able to access variables from parent function (closure) } arrowinner = () => { console.log("printing localvar inside arrow", this.localVar) // 10, as 'this' points to parent function norma } normalinner(); arrowinner(); }


  • Function inside a object case 

let object = {
  localObjVar : 10;
  localObjFn : function() {
    console.log("localObjVar", this.localObjVar); // 10, 'this' points to the object here.
  }
 localObjArrFn : () => {
  console.log("Arrow fn localObjArrFn ", this.localObjVar ) // undefined, as 'this' points to the global scope here.
 }
}

3. Arrow functions are only callable and not constructible.


It only means that Arrow functions cannot be called with new key word, normal functions can be called with new keyword.

let a = new a() // allowed for normal functions, whereas if a is an arrow function then it would throw an error "a is not a constructor".

Thanks for reading!

No comments:

Post a Comment