-2
function doWork() {  
  return function calculate(y) {
     return y + 1;
  }  
}  

var func = doWork();  
var x = func(5);  
document.write(x);  

If var x= func(5), var func=dowork(?);
How do you calculate the "?"

And isn't y undefined in line 2

IZZLIEDAT
  • 11
  • 2

1 Answers1

0

Let's tackle this one bit at a time.

function doWork() {

}

This function stores and returns a nested function called calculate.

function doWork() {
    return function calculate(y) {
         return y + 1;
    }
}

Calculate accepts a parameter in this particular case it's being parsed an integer, simply adding 1 and returning it. In which case if I did console.log(calculate(4)) I would receive the number 5, as I'm parsing in my value, referencing it as 'Y' in the function, adding 1 and simply returning it.

We're then storing the function doWork() in the variable func.

Followed by storing that variable func in to variable x but notice how we are parsing the number 5 when we call var x = func(5) since we have parsed it to the function doWork() we have access to it in our calculate function which is nested && being returned.

We can call var x = func( /* whatever integer we like here */ ) and it will simple return the nested function, with your integer plus 1.

  • You could just remove the nested function and just call `calculate(integer here)`. It would help you understand it easier. –  May 18 '18 at 10:28
  • or does func()= doWork() – IZZLIEDAT May 18 '18 at 10:29
  • Since you've set func to equal doWork(), when you call func, it will run the function doWork. –  May 18 '18 at 10:29
  • [Read this](https://stackoverflow.com/a/111111/5283119) It will probably give you a better explanation. –  May 18 '18 at 10:31