Arrow Function vs Function

Photo by Andrew Neel on Unsplash

Arrow Function vs Function

Did you know arrow function only exists after ES6?

Before you go with the arrow function you should know why you use it and when should we use it.

Arrow function of this will point to upper scope.

Function of this will point to current scope if doesn't bind to any value.

Example of Arrow Function

Current scope is an object that contains a, b, c and arrow function will get the upper scope so it become {} in normal js, it would be window object.

const scope = {
    a: 1,
    b: 2, 
    c: () => {
        console.log(this);
    }
};
scope.c();

// {}

Example of Function

As above said, it will take current scope so will log the whole object.

const scope = {
    a: 1,
    b: 2,
    c: function () {
        console.log(this);
    }
};
scope.c();

// { a: 1, b: 2, c: [Function: c] }

Example of Binded Function

Binded function will only work with 2 condition

  • Bind with a value
  • Function instead of arrow function
const value = 10;
const scope = {
    a: 1,
    b: 2,
    c: (
        function () {
            console.log(this);
        }
    ).bind(value)
};
scope.c();

// 10