Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

377
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda