2

i learn node js with using Video tutorial . I don't get the point of Arrow function .What is the main difference between regular function and arrow function? enter image description here

2 Answers2

4

Arrow functions are a more concise way to write function, introduced in ES6. Arrow functions are anonymous functions, which means you cannot name it.

Example 1:

  var addRegular = function(x, y)  { return x + y };
  var addArrow = (x, y) =>  x + y;

Arrow functions do not bind to this, they don't create their own this, thus the enclosing this is beeing used.

Example 2:

//1. regular function, creates own scope 
function Counter() {
  //set count to 0
  this.count = 0;
  var setOne  = function () {
    this.count = 1;
  };
  setOne(); 
}
var c = new Counter();
console.log(c.count);// outer count will stay unchanged.

//2. arrow function, uses outer this
function Counter() {
  this.count = 0;
  var setTwo = () => {this.count = 2};
  setTwo();
}
var c = new Counter();
console.log(c.count);//will be equal 2.

Arrow functions have an implicit return value, which means there is no need to write return, this makes those function one-liners, as can be seen in the examples above.

Lena Kaplan
  • 756
  • 4
  • 13
2
  1. Lexical this and arguments Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in

  2. Arrow functions cannot be called with new ES2015 distinguishes between functions that are call able and functions that are construct able. If a function is constructable, it can be called with new , i.e. new User() . If a function is callable, it can be called without new (i.e. normal function call). Functions created through function declarations / expressions are both constructable and callable. Arrow functions (and methods) are only callable. class constructors are only constructable. If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.

Ankit Manchanda
  • 562
  • 6
  • 21