Javascript variable is not updating inside function

4k Views Asked by At
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"?

3

There are 3 best solutions below

0
Fullstack Guy On BEST ANSWER

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.

2
Mureinik On

In the first snippet, the parameter hides the number variable - it creates a variable called number which is local to the function, and then updates it.

In the second snippet, the parameter isn't even used, and the number variable is updated directly. You could have written the same function without a parameter:

let number = 100
 
function change() { // No parameter!
    number = number * 10;
}
 
change();
 
console.log(number);
0
Maurice Pheyton On

You can use variables with the same name as the parameters, as the value will be the same anyway, unless the variable with the same name will have a different value than the parameter this is because the function's parameters are already declared as local for this function.