Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In simple terms, what's the difference between a thunk and a Higher Order Function?

I understand that both are functions that return functions.

My experience so far with thunks have been using them to return functions as opposed to just action objects so that I can work with async requests in Redux.

A closure is an implementation of a High Order Function (HOF) in order to create a new scope for private variables...right? Other examples of HOFs include map, reduce and filter.

Is there any thing else that explicitly defines a difference between the two?

Thanks.

like image 431
bloppit Avatar asked Jul 17 '17 13:07

bloppit


1 Answers

I understand that both are functions that return functions

Your understanding is slightly incorrect

  • Thunks can return a value of any type – not just a Function type
  • Higher-order functions can return a value of any type – not just a Function type

My experience so far with thunks have been using them to return functions as opposed to just action objects so that I can work with async requests in Redux.

Thunks (and higher-order functions, for that matter) are not intrinsically related to any particular library (React, Redux) or any particular control flow (sync, async). A thunk is just a nullary function – they have a variety of common uses cases, but most commonly are used to delay the evaluation of a specific computation.

A closure is an implementation of a High Order Function (HOF) in order to create a new scope for private variables...right? Other examples of HOFs include map, reduce and filter.

A closure is not necessarily an implementation of a higher-order function. The function keyword (and => arrow function syntax) does create a closure tho which does have a new (lexical) scope, yes.

Is there any thing else that explicitly defines a difference between the two?

Yes. How they are the same:

  • they are both functions
  • they can both return values of any type

How they are different:

  • thunks are nullary functions (they accept no arguments)
  • higher-order functions accept a function as an argument and/or return a function

Perhaps the most critical distinction:

  • A thunk can only be considered a higher-order function if it returns a function.
like image 189
Mulan Avatar answered Sep 21 '22 20:09

Mulan