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

378
Views
Closure scenario: Why function passed parameter is assigned in closure scope

I am trying to understand how closure works. Please take a look at below code

if (true) {
    let a = 40;

    function add(b) {
        return () => {
            let c = a + b;
            console.log(c);
        }
    }

    console.dir(add(10));
}

Case1: a variable is in block scope

Case2: b variable is in closure scope why? Not understanding

Output:

enter image description here

Please put some light on Case2? why is it so?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

a is in block scope for the anonymous function returned by calling add and b is in the closure scope for the anonymous function returned by calling add

so a function is going to keep any variables needed in the closure scope even when the outer function has exited and all its local variables are garbage collected except b which is needed for the anonymous function . hence it lives in the closure scope of it

hence you may add more to closure scope like so;

if (true) {
    let a = 40;

    function add(b) {
        let d = 55;
        return () => {
            let c = a + b +d;
            console.log(c);
        }
    }

    console.dir(add(10));
}

now in the closure scope we have b and d ( they both are local variables to function add and are needed by the inner function)

similarly if the variable d was not required, then it won't be in its closure scope like so

if (true) {
let a = 40;

function add(b) {
    let d = 55;
    return () => {
        let c = a + b;
        console.log(c);
    }
}

console.dir(add(10));

}

now in the closure scope we only have b.

so its not the function passed in parameter that is assigned in closure scope. it can be any local variable which is needed. for eg:

if (true) {
    let a = 40;

    function add(b) {
        let d = 55;
        return () => {
            let c = a + d;
            console.log(c);
        }
    }

    console.dir(add(10));
}

now we dont have b in closure even it is a passed parameter. its just d in closure scope.

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!