thugsb
thugsb

Reputation: 23426

Javascript global function setting local variable

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

Answers (3)

Kevin Qi
Kevin Qi

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

Daniel A. White
Daniel A. White

Reputation: 190935

Because javascript only works by value, not by reference. See John Hartsock's answer.

Upvotes: 3

John Hartsock
John Hartsock

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

Related Questions