0

I've seen two approaches to writing util functions:

export function func1(arg1, arg2) {
    // do something
}

and the arrow function version

export const func1 = (arg1, arg2) => {
    // do something
};

Why would one use one over the other? Is it just a matter of personal preference?

overdub60
  • 568
  • 1
  • 5
  • 10
  • If you are using context(`this`) inside and this context is meant to be the class and not the function, then you should use arrow function – Rajesh Apr 06 '18 at 08:36
  • The declaration should always be preferred over the assignment, as it will be initialised earlier which is especially important for an export. (Also it's a few characters shorter) – Bergi Apr 06 '18 at 09:09

1 Answers1

0

Arrow functions have different behavior than function declarations / expressions, so lets have a look at the differences first:

Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call). Functions created through function declarations / expressions are both constructable and callable. Arrow functions (and methods) are only callable. class constructors are only constructable. And Lots of other things matter like Callback,prototype etc

Mohammad Raheem
  • 1,060
  • 10
  • 20