let number = 100
function change(number) {
number = number * 10;
}
change(number);
console.log(number);
The above code outputs 100, whereas
let number = 100
function change(blah) {
number = number * 10;
}
change(number);
console.log(number);
outputs 1000
Can someone explain why the number is not updating its value inside the function when the parameter name is also "number"?
The first snippet creates a local variable
numberas the function parameter which shadows the outer variable of the same name.Since JavaScript is pass by value the new variable is assigned the value
100. Since the variable is scoped to the functionchangeand when you update the assignment, the variable defined in the function scope is updated.In the second snippet, you are updating the
numberdefined outside the functionchangedirectly, hence you see the updated value.