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

3
  • 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 Commented Dec 4, 2020 at 18:46
  • Does this answer your question? Does JavaScript pass by reference? Commented Dec 4, 2020 at 18:46
  • Also Is JavaScript a pass-by-reference or pass-by-value language? Commented Dec 4, 2020 at 18:47

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

If change has no params, why are you passing a param in when you invoke it?
@mwilson good catch - a poor copy-paste from the OP's code. Edited and fixed, thanks for noticing!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.