Search code examples
javascriptfunctionreturn

Can you use parent function variables inside a returned function in javascript?


Here's the function code:

function TestFunction(number){
  return function(e){
    return `${number}`;
  }
}

When I use it on google's devtools command line it returns:

function(e){
  return `${number}`;
}

So it looks like the function returned is not created with the number I give to TestFunction, instead it takes the string just like it was written. I have tried to use concatenation instead of interpolation but still not working. What can I do?


Solution

  • There is indeed a closure around the second function, so it will have memory of what num is.

    function a(num) {
      return function b() {
        return `${num}`;
      }
    }
    
    const c = a(6);
    
    console.log(c());