1

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;
}

3 Answers 3

8

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

3 Comments

All arguments in JavaScript are passed by value.
My mistake, you're right. Non-primitives are passed by value as well, but you can modify their properties.
Yup. That's a really frequent argument that pops up, but the key is that the term "call-by-reference" (like "call-by-value" of course) has a pretty specific meaning, and the fact that values can be references to objects is a frequent source of confusion. Too bad they didn't call it "call-by-back-pointer" or something :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.