DEV Community

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

Posted on

1 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay