Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!