DEV Community

Cover image for Difference between Arrow and Normal functions.
Kaushal
Kaushal

Posted on

Difference between Arrow and Normal functions.

Arrow function

  • The arrow functions are work same as with normal functions. It was introduce in ES6.
  • Syntax const variable = () => {}
  • Ex
    var foo = _ => 'Hii';

  • It's same as
    function name(params) {
    return 'Hii';
    }

  • These arrow functions are make eassy our work and readablity.

  • Normal function

    • var foo = function(name) { return function(age) { return function(city) { return ${name} ${age} ${city} } }

    }

  • Arrow function

    • var foo = (name) => (age) => (city) => ${name} ${age} ${city};

Difference between normal and arrow functions.

    var name = "Mike";
    var obj = {
        name: "Tom",
        foo: function() {
            console.log(this);
            var bar1 = function() {
                console.log(this.name); // Point to Window(Parent)
            }
            var bar2 = () => {
                console.log(this.name); // Point to current Object
            }
            bar1();
            bar2();
        }
    }
    obj.foo();
    // If we not use var it point to parent
    var bar = () => {
        var x= "sad";
        let y= "sasa";
        console.log(this.x); // Window // undefined
        console.log(this.y); // sasa
    }
    bar();

Why we need Arrow function.

  • Arrow functions cannot called with Constructer.
  • Arrow functions are not having their own this. So, we cannot update using this.
    • Whenever we use this inside the arrow function it will check parent, until not find parent.
    • Arrow alway have lasical scope.

When use it.

  • Use arrow function only when you have to use parent's this.
  • Use only when we need it, according to requirenment.

Not use.

  • It has not thier own this so we can not call it as a Constructor

Top comments (0)