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

155
Vistas
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 Respuestas
Responde la pregunta

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