DEV Community

Discussion on: Closures in Javascript

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."