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

110
Visualizações
Is a closure only created when a inner function returns something?

I have been playing around with closures a little bit and I have a difficult time understanding what's the difference between lexical scoping and closures.

In the examples below both child functions are able to reach the a variable thanks to lexical scoping. Now I wonder where exactly is the closure created in the second example? Is it because of the childFunc() being returned directly, or is it because of childFunc() being stored in a seperate child variable before being exectuted?

Example 1: No closure

function parentFunc() {
    let a = 10;

    function childFunc() {
        console.log(`hey from child func Mr. ${a}`);
        a++;
    }
    childFunc();
}
console.dir(parentFunc) //closure not part of the Scopes

parentFunc() //doesn't increment a
parentFunc()

Example 2: Closure

function parentFunc() {
    let a = 10;

    return function childFunc() {
        console.log(`hey from child func Mr. ${a}`);
        a++;
    }
}
const child = parentFunc()
child(); // increments a
child();

console.dir(parentFunc) //closure is part of the scopes
about 4 years ago · Juan Pablo Isaza
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