Thursday, July 02, 2020

Subtle Difference between NodeJS function and Arrow function.

There are 2 ways to define a function in NodeJS:

  • to define with the function keyword
  • to define with arrow "=>" keyword 

However, the functions defined by the two ways differ very subtly. Considering the .bind function on a function, which assigns an object as this of the function. the .bind function is available at functions created in both ways, but the function defined with arrow will not have access to this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

This snippet demonstrated that after calling .bind, the arrow create function still doesn't have access to the correct this object. (verified in NodeJS v13.10.1)