DEV Community 👩‍💻👨‍💻

Alexx Martínez
Alexx Martínez

Posted on

Explain Thunks in JavaScript Like I'm Five

Top comments (8)

Collapse
 
glebec profile image
Gabriel Lebec

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.

Collapse
 
nestedsoftware profile image
Nested Software

Thanks Gabriel, that article looks really good!

Collapse
 
nestedsoftware profile image
Nested Software

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.

Collapse
 
alexxmart profile image
Alexx Martínez Author

Very helpful, thanks!

Collapse
 
andy profile image
Andy Zhao (he/him)

TIL "thunk" is an actual programming word.

Now I sit here and wait for answers. 😁

Stephen Colbert eating popcorn with 3D glasses and smirking

Collapse
 
rhymes profile image
rhymes

Same, first time I hear about it :-O

Collapse
 
mrjjwright profile image
John Wright

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.

Collapse
 
mohnmu profile image
Mohn

thunk is a function that encapsulates some other function .

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠