kofifus kofifus - 6 months ago 12x
Javascript Question

ES6 arrow function with no parameters


function f() { ... }

and another function dosomething expecting a function like f

function dosomething(callback) { ...; callback() }

that expects f (an example of dosomething can be setTimeout)

calling dosomething and passing f, is there a difference between:



dosomething(() => f());

is any of these options preferable ?


That the wrapping function (second example) is an arrow function or not does not change a thing here.

However, this wrapping function can be useful to forbid arguments transfer: in the first case, if callback is called with an argument, it will be given to f. Not in the the second case. An alternative could be to restrict the number of transmitted arguments: dosomething((a, b) => f(a, b));.

It can also be used to protect against this injection: in the first case, doSomething can bind f to change its this (callback.bind(whatever)). With a wrapping function (arrow or not), it won't have any effect and f will keep his this (the global context) whatever doSomething does.