0

I came across this while watching a video and though they did a good job explaining closures, they did not really explain how the functions were linked. So, I still did not understand how calling newFunction('inside') somehow set the values for both outerVariable and innerVariable. Can anyone explain how this works? Here's the code:

function outerFunction(outerVariable){
    return function innerFunction(innerVariable) {
        console.log('Outer Variable ' + outerVariable)
        console.log('Outer Variable ' + innerVariable)

    }
}

const newFunction = outerFunction('outside')
newFunction('inside')
Jay 777
  • 11
  • 1
  • *"how calling newFunction('inside') somehow set the values for both outerVariable and innerVariable"*: calling `newFunction` does not set the value for the `outerVariable`. That variable was set by calling `outerFunction`, and is still available to `innerFunction` whenever it gets called. – trincot Oct 27 '21 at 21:04
  • Thank you for the reply. And how does newFunction set innerVariable? – Jay 777 Oct 27 '21 at 21:10
  • `innerVariable` is set when `newFunction` is called. `newFunction` refers to the *same* function that `innerFunction` refers to. – trincot Oct 27 '21 at 21:17

2 Answers2

0

This line:

newFunction('inside')

does not set outerVariable. What happens here is a classic javascript closure. A closure gives you access to an outer function’s scope from an inner function.

In this case:

const newFunction = outerFunction('outside')

will return a new function (in our case its innerFunction) and innerFunction when called will have access to its to its surrounding state (the lexical environment). In this case, our surrounding state is outerVariable variable.

So basically, at this point its similar to this:

var outerVariable = "outside"
function innerFunction(innerVariable) {
        console.log('Outer Variable ' + outerVariable)
        console.log('Outer Variable ' + innerVariable)

    }

And when you call innerFunction with "inside", ofc innerVariable will be "inside" and outerVariable will have a value of "outside".

munleashed
  • 1,677
  • 1
  • 3
  • 9
0

This is a classic closure. when you called the outerFunction in this line: const newFunction = outerFunction('outside')

newFunction saved innerFunction as the return value. The principle of closure makes sure that newFunction also received all the execution context of innerFunction along with it. Which means that it receives the variable outerVariable which has the values outside that got passed to it in the above line. Thats how it can print not only innerVariable which you passed while invoking newFunction but also the value of outerVariable.

Anshu Jain
  • 239
  • 1
  • 3