Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
How does calling one function set the variable of another in javascript?

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')
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!