DEV Community

Closures in Javascript

Damien Cosset on February 18, 2019

Introduction You may have heard about closures. You most certainly already use them even if you don't fully know what they are. Closures...
Collapse
 
wizardrogue profile image
Joseph Angelo Barrozo

Learned a lot! Thanks!

Collapse
 
sagar4u profile image
sagar4u

Closure is one of those things which causes my head spinning.
Nice article. Learnt a lot. Thank you.

Collapse
 
damcosset profile image
Damien Cosset

Glad you found it helpful :)

Collapse
 
moopet profile image
Ben Sinclair

If anyone does foo(bar)(baz) in code I have to maintain, I'm going to be cross.

Collapse
 
damcosset profile image
Damien Cosset

Yeah, I can understand that :D

Collapse
 
yes_himanshu profile image
Himanshu

Very well explained with examples in following link
idontknowjavascript.com/2019/05/cl...

Collapse
 
nym02 profile image
Nayeem M. Muzahid

Can anybody explain this to me? cookiesBaker("Sarah")("peanut butter")

Collapse
 
saberhosneydev profile image
Saber Hosney

Given this is the definition of cookiesBaker function

let cookiesBaker = function(cook){
    return function(secretIngredient){
        return function(chocolate){
            return `${cook} cooked a ${secretIngredient} ${chocolate} chocolate cookie.`
        }
}
Enter fullscreen mode Exit fullscreen mode

As you can see here, there's 3 functions, one with two nested functions. each one of em takes a parameter. so we need to call the function with three different nested parameters in order to meet its requirement.
like so cookiesBaker("Sarah")("peanut butter")("white") which will return a value of "Sarah cooked a peanut butter white chocolate cookie."
How it worked?
cookiesBaker("Sarah") calling this alone will evaluate and set parameter "cook" equal to "Sarah" then returns a function. in which that function will be called as following cookiesBaker("Sarah")returnedFunction("peanut butter") which will evaluate parameter "secretgradient" to "peanut butter" then returns a function that will be called as cookiesBaker("Sarah")returnedFunction("peanut butter")returnedFunctionTwo("white") which will evaluate parameter "chocolate" to "white" then returns a string value equal to "Sarah cooked a peanut butter white chocolate cookie."