Are JScript strings passed by reference?

I asked “are JScript strings passed by reference (like
JScript objects) or by value "urn:schemas-microsoft-com:office:office" /> (like
JScript numbers)?”


question!  It doesn’t matter, because
you can’t change a string.  I mean, 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
in JScript are like numbers — immutable primitive values.


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.

Comments (4)

  1. Thanks for the earlier reply. I think I get your point.

    Regarding your comment about having to pass strings somehow and generally doing it by reference "where possible", have you got an example of where it is not possible? Can I inadvertently cause my strings to be passed (slower) by value?


  2. Eric Lippert says:

    Strings are pretty much always _passed_ by reference, but often the first thing that the callee does is make a copy anyway. The script engines use BSTRs to store strings and BSTRs are not reference-counted, so any time the callee needs to, say, set a property, it needs to make a copy.

    I see what you’re getting at though, and yes, there are plenty of times that you end up copying a lot of string data around. That’s a good subject for tomorrow’s post; I’ll see if I can find any old email from a few years back when I did a lot of work in this area.

  3. John says:

    Ok, first off, my little experiance with JScript tells me that they are passed by reference. But, the comment above about it "dosn’t matter" is complete BS. It matters quite a bit. Say you have an array of objects, and you want to fill the objects with data from a database. Say they contain mostly strings. Try this. Query your database, get a recordset, and set the strings in the object, to those returned by the record set. When you get done, all your objects will have null strings. Why? Becuase the strings were passed by reference, and the moveNext method on a record set does change the string values!

  4. Eric Lippert says:

    I suspect that you’re confusing two different usages of the term "by reference". When I asked whether JScript strings were passed by reference, I meant whether the STRING ITSELF was passed by ref or by value. You’re talking about whether the MEMORY ADDRESS that holds the string is passed by value or by reference, which is a subtly different thing.

    JScript passes objects by reference and numbers by value, but doesn’t support passing references to variables at all.

    Confused? It’s a confusing topic. I wrote an article about the difference here: