I know Javascript always passes objects by reference. But what about the other types?
number – ?
string – Immuteable, so it shouldn’t matter
object – ref
array – ?
function – ?
regexp – ?
I came to the conclusion that not all values in Javascript can be objects nor can they be pass by reference with the following code:
function SomeFunc(func) {
var numba = 0;
var innerFunc = function() {
numba = func(numba);//try commenting me out and switching to next line
//func(numba);//numba fails to increment
return numba;
};
return innerFunc;
}
//this variable should persist the numba variable through closure. Incrementing each call by 1.
var closure = SomeFunc(function(numba) {
numba = numba + 1;
return numba;
});
document.writeln(closure());
document.writeln(closure());
document.writeln(closure());
Because numba fails to increment, unless I return the number and updated the variable in closure…then that tells me this is not pass by reference. Am I missing something?
or take the very basic
function UpdateNumber(numba) {
numba = 10;
document.writeln('in func number becomes ' + numba);
}
var numba2 = 5;
UpdateNumber(numba2);
document.writeln('back to caller number is ' + numba2);
//in func number becomes 10
//back to caller number is 5
No. JavaScript always passes by value, not by reference.
People often confuse the ability to modify an object in a method and have the modification be visible on the outside as being pass by reference. This is not the case. Pass by reference means modifying what the value points to is visible outside the function. For example
In this example if JavaScript implemented pass by reference then
x === 42would be true. However it’s not. The variablexwould still have the value{}