2

Code 1 prints "florence"

let name = "florence";

function test (arr) {
  arr += " and the machine";
}

test(name);

console.log(name);

Code 2 prints "florence and the machine"

let name = ["florence"];

function test (arr) {
  arr[0] += " and the machine";
}

test(name);

console.log(name);

I understand that the outcomes are different because Code 1 passes by value, and Code 2 passes by reference. I'm just trying to understand why.

  1. What is the benefit of retaining the mutability of an array, but not a variable?
  2. CAN YOU pass variables by reference?
  3. CAN YOU pass arrays by value (without a workaround)?
  • 4
    1. it's not Arrays, it's ALL objects (Array is an Object after all) 2. no, 3. `fn([...array])`, for an object it'd be `fn({...object})` ... Note: these are both shallow copies - but I guess this is a "workaround" ... javascript works as it works ... how do you expect to change how it works "without a workaround" – Bravo Jun 26 '22 at 05:38
  • 2
    Passing a copy of the array (that could contain 1000's of items) could take a while and waste memory – Hans Kesting Jun 26 '22 at 05:54
  • 1
    Actually strings are passed by reference it's just it has reference counts internally to know when to copy. But the answer to your question, Speed, if everything was passed by value it would have a dramatic effect on performance.. – Keith Jun 26 '22 at 06:49
  • @Keith I'd rather argue strings are passed by value, like everything else, and that in most engines a string is implemented as a pointer, but that doesn't really matter since after all strings are immutable and we don't care how they're implemented under the hood. At least not when discussing call-by-value. – Bergi Jun 26 '22 at 06:55
  • @Bergi lol, classic Berg, be obtuse when you knew exactly what I was saying. I personally think knowing passing strings to functions is pretty much a zero cost, so knowing this is certainly something useful. – Keith Jun 26 '22 at 07:07

1 Answers1

0

When you pass an object (array), the referrnce to the object is passed, so in your case arr points to name.

arr[0] however now points to the value at name[0], and name[0] is modified accordingly.

Changing arr has no global effect:

let name = ["florence"];

function test (arr) {
  arr[0] += " and the machine";
  arr=[];
}

test(name);

document.write(name);
JMP
  • 4,417
  • 17
  • 30
  • 41