In Javascript, you can reassign a variable like:
var x = 10;
x+=10;
console.log(x);
//prints 20 to the console
But if I take another example of a seemingly similar activity I get an unexpected result:
var originalVar = 1;
changeMyVar(originalVar);
function changeMyVar(myVar) {
myVar += 1000;
return myVar;
}
console.log(originalVar);
//prints 1 to the console
I see this as one in the same. I am passing my variable as an argument into a function. I'm reassigning the value within that function. And then I'm returning and printing that variable. Where is the mutation?
Primitives as function parameters are passed by value in javascript. Therefore myVar
in changeMyVar
function is not reference to originalVar
but new variable with value of originalVar
.