Please explain this Javascript closure exercise

closures, javascript

Solution

In order to understand this you must know what is the difference between a function call and a reference to a function. As well as how scopes work in javascript.

Assuming you do know these things, let's get explaining.

So you first have a variable `hidden` that is being assigned a value of `mystery(3)`. So immediately look at the function `mystery` and see what it returns. it returns a reference to an inner function `mystery2`. So now `hidden` holds a reference, meaning that it has no actual numeric value. Following you have a second variable declaration ` var jumble = mystery3(hidden);`. Now in order to know what `jumble` holds you need to look at the function `mystery3` and the value it returns. It, again, returns a reference to an inner function `mystery4`. So now the two variables you have contain references to inner functions of the closures `mystery` and `mystery3`.

Now let's have a look at `var result = jumble(2)`. Executing `jumble(2)` is an actual function call to the function that `jumble` holds a reference to, which is `mystery4`. When `mystery4` runs you see it requires a parameter `bonus`, which will be `2` given from the line `var result = jumble(2)`. It returns `param(6) + bonus`. `bonus` is `2`, ok, but what is `param(6)`? That is the value given to `jumble`: `hidden`, which was a reference to `mystery2`, remember? So running `param(6)` will execute `mystery2` with a parameter `6`

And so, tracing back the functions may have turned out a little confusing, but let's follow that with actual values to make it a little clearer ( if that's even a word ).

Executing `var result = jumble(2)` will give us a return value of `param(6) + 2` to get `param(6)` we go into `mystery2` with `multiplier = 6`, where we set `multiplier = 6 * input`. Our input is equal to `3+2=5`, so `multiplier` becomes `6*5=30` and as a return value we multiply that by `4` which is our `var secret`. By the end of the execution of `mystery2` we have a value of `120`, which is returned to our `param(6)` in `mystery4`. And if you remember that our `bonus` was `2`, `120+2=122` Voila!

I get the feeling I didn't do a very good job at explaining this simply, but that's probably the best I could do. Hope that helped!

Problem

I'm a javascript noob trying to wrap my head around the closure exercise below. Now, I know the result is 122. Can anyone walk me through this step by step (what gets passed to what), so I can understand how closures work? ``` var hidden = mystery(3); var jumble = mystery3(hidden); var result = jumble(2); function mystery ( input ){ var secret = 4; input+=2; function mystery2 ( multiplier ) { multiplier *= input; return secret * multiplier; } return mystery2; } function mystery3 ( param ){ function mystery4 ( bonus ){ return param(6) + bonus; } return mystery4; } ```

Original source

Related problems