Difference between regular functions and arrow functions?

Hi, I’m going to describe the main characteristics of each one.  

Arrow functions 

  • Is a popular feature of ES6.
  • The syntax is much shorter
myArrowFunction = () => {
  return "Hello World!";
}
  • If the function has only one statement, we can write the code like this:
 myArrowFunction = () => "Hello World!";
  • Are anonymous, this means that doesn’t have name. 
  • Arguments are not binding in arrow functions.
  • No binding of “this” keyword, means that the arrow functions does not have its own “this”; uses the value of the execution context that contains it (scope in which it was defined).  Look the example:
function Person(){
  this.age = 0;

  setInterval(() => { // Arrow function
    this.age++; // |this| points to Person object
    console.log('this.age ===>', this.age); // 1, 2, 3...
  }, 1000);
}

var p = new Person();

when should I not use arrow functions?

Well, arrow functions does not replace regular functions, for example if you are working with object methods, the “this” keyword never will inherit the value from its parent scope, look:

let animal = {
  legs: 0,
  createLegs: () => {
    this.legs++; // this is not bound to anything
  }
}

So, you can use arrow functions with anything that requires “this” to be bound to the context, and not to the function itself.

Regular functions

  • Syntax 
var myRegularFunction = function(x, y) {
  return x + y;
};
  • Arguments are binding in regular functions, see the example:
let myRegularFunction = {  
 showArgs() { 
  console.log(arguments); 
 } 
}; 
myRegularFunction.showArgs(1, 2, 3, 4);
  • Regular functions have their own this. 
let im = {
 name: "Cristina Rojas",

 regularFunction() {
   console.log("My name is " + this.name); 
   // My name is Cristina Rojas
 }
};

im.regularFunction();
  • Regular functions are constructible, this means that can be called using the new keyword. 
function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| points to Person object
    console.log('this.age ===>', this.age); // 1, 2, 3...
  }, 1000);
}

var p = new Person();

But if we are trying to use new with using an arrow function this will be through us an error (…is not a constructor at <…>)

By Cristina Rojas.