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

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

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 Relatório

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 Relatório

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