nomac10
nomac10

Reputation: 23

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

Upvotes: 0

Views: 57

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370799

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.

Upvotes: 1

Related Questions