Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

379
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda