You don't pass by reference in JS. You pass references by value.
Passing by reference has a well defined meaning in computer language terminology. It means passing something that references the variable outside the function. Something you can't do in JavaScript
void someFunc(ref int v) {
v = 456;
}
var foo = 123;
someFunc(foo);
write(foo); // output 456
Above we are not passing 123 (the value of foo) into someFumc, we are passing a reference to foo. This is what pass by reference means.
same if foo was reference to an object
void someFunc(ref Object v) {
v = someOtherObject;
}
var foo = someObject;
someFunc(foo);
// foo now refers to someOtherObject
In this impossible in JavaScript. It does not have the concept of pass by reference. It only has pass by value
function someFunc(v) {
v = someOtherObject;
}
var foo = someObject;
someFunc(foo);
// foo still refers to someObject
Above the value of foo, which is a reference to someObject, that value is assigned to v in someFunc. v's value is set to reference someOtherObject. foo's value is still someObject as there is no way to "pass by reference" in JavaScript
I would argue that Javascript is a hybrid of pass by reference because of the case below though.
function someFunc(v) {
v.myvar = 456;
v = someOtherObject;
}
var foo = someObject;
foo.myvar = 123;
someFunc(foo);
// foo still refers to someObject
// foo.myvar is 456
Banning our team from passing objects around except in specific, discussed, cases got rid of lots of difficult to track down bugs.
You'd be wrong. Again "Pass by reference" is "well defined" in computer languages.
Passing a reference to an object is not "pass by reference". Your example works the same in Java and C# and probably Swift and many other languages. But you aren't "passing by reference". "pass by reference" specifically means passing a reference to the variable, not the variable's value. Javascript always passes the value of the variable, it has no ability to pass a variable by reference.
Great explanation of something that has caught me out multiple times (I occasionally dabble in JS).
Having spent my career in languages with pass by reference it feels unnatural not to have it. I suspect if I started with JS this wouldn't be such a problem.
Passing by reference has a well defined meaning in computer language terminology. It means passing something that references the variable outside the function. Something you can't do in JavaScript
Above we are not passing 123 (the value of foo) into someFumc, we are passing a reference to foo. This is what pass by reference means.same if foo was reference to an object
In this impossible in JavaScript. It does not have the concept of pass by reference. It only has pass by value Above the value of foo, which is a reference to someObject, that value is assigned to v in someFunc. v's value is set to reference someOtherObject. foo's value is still someObject as there is no way to "pass by reference" in JavaScript