1
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"?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Thamjith Thaha
  • 45
  • 2
  • 13
  • 3
    When you name your parameter `blah`, `number` is not defined anywhere inside the function, so it refers to the global variable. When you name the parameter as `number`, it becomes a local variable, which won't affect the global one – blex Dec 04 '20 at 18:46
  • Does this answer your question? [Does JavaScript pass by reference?](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference) – crashmstr Dec 04 '20 at 18:46
  • Also [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – crashmstr Dec 04 '20 at 18:47

3 Answers3

2

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.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

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);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

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.