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

130
Visualizações
Javascript hoisting and scoping
function sayHi(name){
   let result="Hi"+name+a;
   console.log(result)
}

let a=1;
sayHi("Alex")

The result of the above code is Hi Alex1, so from what I understand is the variable a is hoisted, but in JS, only the declaration is hoisted, not the initialisation, so how come the result can use the value of a?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Because the value is set before the operation is called. Look at the order of these two things:

let a=1;
sayHi("Alex")

First the value of a is set to 1, then the function sayHi is invoked. Within that function the value of a is used.

Swap the two statements and see a different result:

function sayHi(name){
   let result="Hi"+name+a;
   console.log(result)
}

sayHi("Alex")
let a=1;

about 4 years ago · Santiago Trujillo Relatório

0

Functions don't try to access variables until they are called, which happens after the a variable has had a value assigned to it.

about 4 years ago · Santiago Trujillo Relatório

0

Javascript works like a waterfall. This means code will be compiled from the higher level. The variable a is initialized before the function sayHi is called: so you have access to his value. Check how scope works as well here https://www.w3schools.com/js/js_scope.asp

about 4 years ago · Santiago Trujillo 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