re: Named functions vs Functions as variables in JavaScript VIEW POST


For plain JS I typically prefer named functions for readability, but if using TypeScript I often notice that certain types of functions arise often - when a function itself can be considered a domain object (i.e. it has a specific call signature that is meaningful in the problem space), I usually use a function variable because that allows me to use a descriptive type that provides better context than just "function." For example, in a redux application you might have a type for a reducer:

type Reducer<S = {}, A extends Action = {}> = (state: S, action: A) => S;

Then, you can use the type to describe your reducer function:

// using traditional function keyword
function myReducer(state, action) {
  return { ...state, ...action };

// vs...

type MyReducer = Reducer<MyState, SomeAction>;

const myReducer: MyReducer = (state, action) => ({ ...state, ...action });

Definitely more verbose, perhaps even less readable. But to me, it's worth it for the added type safety (YMMV)

code of conduct - report abuse