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

133
Visualizações
I was going through the topic "Closures" in JS, and tried to do some experiment with this concept. I created two Function and checking there output

both function print the value inside the "outer" and "inner" function twice.

using simple function declaration & execution

function outer1() {
  var j = 20;

  function inner1() {
    var k = 30;
    console.log(j, k);
    j++;
    k++;
  }
  inner1(); //calling inner1 
  return;
}

outer1(); // calling function 2 times
outer1();

output : // same output both time
20 30
20 30

-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x//

using function expression

function outer() {
  var a = 20;
  var inner = function() {
    var b = 30;
    console.log(a, b);
    a++;
    b++;
  }
  return inner; //returning inner
}

var func = outer();

func(); // calling function 2 times
func();

output : // value of a is incremented by 1 time.
20 30
21 30

I am confused, why both are showing different result ?, why output remain same for the first one but different for second one ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

With the first example, you run outer() multiple times. This creates a new inner function each time, each with the initial value of j.

If you're familiar with classes, this is kind of like calling new Thing().do(); new Thing().do(); vs const thing = new Thing(); thing.do(); thing.do();

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