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 number
as 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 function change
and when you update the assignment, the variable defined in the function scope is updated.
let number = 100
function change(number) {
//This is the variable scoped to the function
number = number * 10;
}
//This is the variable defined in the global scope
change(number);
console.log(number);
In the second snippet, you are updating the number
defined outside the functionchange
directly, hence you see the updated value.