Reputation: 23426
Why does this return 'foo', not 'foobar'? I need function g to modify (non-global) var v, yet function g is a global function. Thanks.
f();
function f() {
var v = 'foo';
g(v);
alert(v);
}
function g(v) {
v = v+'bar';
return v;
}
Upvotes: 1
Views: 806
Reputation: 3260
Primitive ALL arguments in javascript (the string argument to g, in this case) are pass-by-value instead of pass-by-reference, which means the v
you're working with in function g(v) is a copy of the v
in function f.
Edit:
all arguments are passed by value, not just primitives.
Upvotes: 1
Reputation: 190935
Because javascript only works by value, not by reference. See John Hartsock's answer.
Upvotes: 3
Reputation: 86872
Because you return v from g(v) call but you do not reassign v
f();
function f() {
var v = 'foo';
v = g(v); //you need to assign what is returned
alert(v);
}
function g(v) {
v = v+'bar';
return v;
}
Upvotes: 8