May 2nd, 2020
JS arrow or normal function
img

Normal function is ES5 style and arrow is the new ES6 styles.

The Syntax difference

Copy 📋
function A() {
  // ES5 way
  return 10;
}

const B = () => {
  // ES6 way
  return 10;
};

Application difference: This key word

Copy 📋
const parentA = {
  val: 20;
  A: {
    val: 10,
    getVal: function () { //ES5 way
      return this.val; //10
    }
    getVal: () => { //ES6 way
      return this.val; // undefined, be careful this might be this of the parent
    }
  }
};

So this will always be unusable in ES6?

No

Arrow function syntax uses "lexical scoping" to figure out what should be "this". Lexical scope is a fancy way of saying it uses this from the surrounding scope.

The confusion of this with arrow with this

Copy 📋
function A() {
  return {
    a: 10,
    getVal: function getA() {
      console.log(this.a); // here we can access this.a
      const funArray = () => {
        return this.a; // so this arrow function can also access this.a
        // arrow function lexically taking this from the time it was created
      };
      return funArray;
    },
  };
}

console.log(A().getVal()()); //10 10