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

156
Visualizações
Variable initialized with let is not changing?

My code is returning an empty array from main and then [foo,bar,baz] on the console log after main is called. Was the original array not changed inside of main? When I remove the arr function both console logs return an empty array. Is it because the function arr is a callback for console? If someone could explain why the function arr is affecting the output that would be great thanks.

let arr = ['foo', 'bar', 'baz'];
function main() {
   arr = [];
   function arr() {
      const result= 8
      return result;
    }
   console.log(arr);
}
main();
console.log(arr);

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

0

You created another variable named arr inside the function, so all references to arr inside the function refer to that new variable (which is only scoped to the function), and the outside arr remains unchanged. Your code is equivalent to

let arr = ['foo', 'bar', 'baz'];

function main() {
  // new variable for this scope:
  let arr;
  // function declaration is hoisted:
  arr = function arr() {
    const result = 8
    return result;
  }
  // assignment runs:
  arr = [];
  console.log(arr);
}
main();
// but arr outside remains unchanged because it's a different binding
console.log(arr);

This is one reason why it's important to give variables meaningful names. A function is not an array, so it probably shouldn't be named arr unless you're deliberately trying to confuse readers of the code.

You can also help prevent yourself from making this sort of mistake by using the ESLint rule no-shadow, which prevents inner scope variables from having the same name as an outer scope variable.

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