Yesterday I asked “are JScript strings passed by reference (like objects) or by value (like numbers)?”
Trick question! It doesn’t matter, because you can’t change a string. Suppose they were passed by reference — how would you know? You can’t have two variables refer to the “same” string and then change that string. Strings are like numbers — immutable primitive values. (Note that JavaScript, unlike VBScript, does not support passing variables by reference at all. The question here is about whether the value passed as an argument is a reference to the string or a copy of the string.)
Of course, “under the covers” we actually have to pass the strings somehow. Generally speaking, strings are passed by reference where possible, as it is much cheaper in both time and memory to pass a pointer to a string than to make a copy, pass the value, and then destroy the copy.
That said, unfortunately there are scenarios in which strings are passed by reference, and then the callee immediately makes a copy of the string. Strings are represented internally as BSTRs which are not reference counted, so you have to make a copy if you want to express ownership.
Pingback: Porting old posts, part 1 | Fabulous adventures in coding