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

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

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 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