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

188
Visualizações
JavaScript: Order in which variable assignment takes place

I'm new to JavaScript and would like to understand the order in which variable assignment takes place. Let's assume I have the following toy example:

var foo = document.sentence.split(',');

Do we split the sentence first, then assign the output of split to the foo variable? Or, do we first create the foo variable, and then assign the output of document.sentence.split(',') to foo?

Thanks!

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

0

With var things are a little different, because of hoisting.

Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.

However JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.

Example:

'option strict';
function myFunction() {
  console.log(foo);
  // => undefined
  var sentence = 'my,array,of,strings';
  var foo = sentence.split(',');
  console.log(foo);
  // => ['my', 'array', 'of', 'strings']
}
myFunction();

On the first console.log(foo) we didn't get a Uncaught ReferenceError: foo is not defined error. That's what would normally happen if we tried to access a variable that hadn't been declared yet.

If we try the same thing using const (or let), we get a different response:

'option strict';
function myFunction() {
  console.log(foo);
  // => Uncaught ReferenceError: Cannot access 'foo' before initialization
  const sentence = 'my,array,of,strings';
  const foo = sentence.split(',');
  console.log(foo);
  // => ['my', 'array', 'of', 'strings']
}
myFunction();

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