Explain Thunks in JavaScript Like I'm Five
Alexx Martínez

Alexx Martínez @alexxmart

About: I'm a web and react-native developer with 2+ years of professional experience working with local and remote teams of different backgrounds in the computer science field.

Location:
El Salvador
Joined:
Jun 26, 2017

Explain Thunks in JavaScript Like I'm Five

Publish Date: Mar 29 '18
9 8

Comments 8 total

  • Andy Zhao (he/him)
    Andy Zhao (he/him)Mar 29, 2018

    TIL "thunk" is an actual programming word.

    Now I sit here and wait for answers. 😁

    Stephen Colbert eating popcorn with 3D glasses and smirking

    • rhymes
      rhymesMar 31, 2018

      Same, first time I hear about it :-O

  • Nested Software
    Nested SoftwareApr 1, 2018

    I'm not sure where the term came from, but it appears to be nothing more than a function that you return from another function, e.g:

    const f1 = () => {
        const f2 = () => console.log('f2 called')
        return f2
    }
    
    const f2 = f1() // obtain the 'thunk'
    f2() // call the 'thunk'
    

    This appears to be used in redux and they call it a 'thunk'. It's a piece of logic you can run at some later time rather than right away.

    I found an article introducing the use of 'thunks' in redux.

  • Gabriel Lebec
    Gabriel LebecJun 3, 2018

    You may be interested in my article Thunks in Redux: the Basics.

    @nestedsoftware : an unevaluated function body is one way to have a thunk in JS, but the concept of a thunk is more general than that. In essence, a thunk is a piece of unevaluated (i.e. lazy) code, which can optionally be evaluated as needed if it turns out the result is going to be used.

    • Nested Software
      Nested SoftwareJun 3, 2018

      Thanks Gabriel, that article looks really good!

  • Mohn
    MohnSep 23, 2019

    thunk is a function that encapsulates some other function .

  • John Wright
    John WrightMay 30, 2021

    From Wikipedia:

    In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine. They have many other applications in compiler code generation and modular programming.

    The term originated as a humorous, incorrect, past participle of "think". That is, a "thunk value" becomes available after its calculation routine is thought through, or executed.

Add comment