DEV Community

Discussion on: Everything you should know about Javascript functions

Collapse
 
ihusnja4 profile image
Ivan

An arrow function is nothing more than the shorter syntax for declaring function expression.

This statement is incorrect. Though arrow function can be used for this purpose, its primary purpose is sharing context (this) with parent scope, which makes such functions ideal for passing as arguments to when calling function that can then execute it.

Prior to arrow functions introduction we would have to bind a function context when passing it as argument, as context would be lost otherwise.

class Greeter {
    greeting = 'hello';
    say1 = (name) => this.greeting + ' ' + name;

    say2(name) {
        return this.greeting + ' ' + name;
    }
}
function sayHi(name, greeterFn) {
   console.log(greeterFn(name));
}

var greeter = new Greeter();

sayHi('Bob', greeter.say1); // 'hello Bob'

// context is lost when passing function as argument of another function
sayHi('Bob', greeter.say2); // ' Bob'

// bind context
sayHi('Bob', greeter.say2.bind(greeter)); // 'hello Bob'
Collapse
 
duomly profile image
Duomly • Edited

Thanks for pointing that. You are right. I should mention this :)

Collapse
 
danielsan profile image
Daniel Santana

The over simplification of what arrow functions are is really concerning for an article with such an audacious title.

There’s no mention of the fact that this within an arrow function will always try to find the nearest defined this at that scope.

No mention of the fact that bind is still there and you can still bind arrow functions for achieving some sort of currying approach.

Also there’s no mention that the keyword arguments will behave just like the keyword this, and not like a regular function.

And last but not least, there’s no mention of some of the nicest things about the arrow functions which is the possibility of not using the return keyword

I vouch for a more humble name for the article.