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

147
Vistas
JavaScript running order questions

I have a very simple Javascript code, can't fully understand the running order and output.

function f1() {

    n = 999;

    change = function() {
        n = "Barry";
    };
    return change;

}

var result = f1();

result(); 
console.log(n)
change();
console.log(n)

Output:

Barry
Barry

As my understand, I define a globale variable n, and n = 999. Then I create a function which will define globale n to "Barry". and assign this function to change. and return this change variable.

Then I trigger this f1(), and give change to result. At this timepoint the change is a function but not runs yet.

So why the first Console.log return my Barry? Then change has not runs yet..

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are not properly declaring your variables in the scope with either var, let or const so it is polluting the global or outer scopes.

n is changed because result === change and change sets n to Barry.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The reason for this behavior is at this line ,

var result = f1(); // n - 999

At this point you are calling the inner function and setting the n to Barry

result(); // n - Barry

I am not sure how you calling this function directly. But hope it's just a pseudo code

change(); // n - Barry

Which means,

 result() === change()
about 4 years ago · Juan Pablo Isaza Denunciar

0

why the first Console.log return my Barry? Then change has not runs yet..

Yes it has, you are only calling console.log after having called result(). Try the following:

var n, change;
function f1() {

    n = 999;

    change = function() {
        n = "Barry";
    };
    return change;

}

console.log(n);
var result = f1();
console.log(result === change);
console.log(n);
result(); 
console.log(n);
change();
console.log(n);

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