Search code examples
javascript

Does passing a string to a function copy it by value or pass it by reference?


Since strings in JavaScript are basic types, does passing a string to a function create a local copy of it? I'm wondering about this since you can't modify strings after they've been created, so it would seem illogical that JavaScript VMs wouldn't just pass the string's address to the function internally.

If anybody is going to tell me that i shouldn't worry about this (this happens a lot when talking to web developers), I'm working on HTML5 games and garbage collection is a major concern, so i really need to know.


Solution

  • The string will be passed by reference.

    A string is not mutable so whenever you try to change it you get a new string (eg. by doing value+="more").

    Also see: What does immutable mean?

    @T.J. Crowder: by value vs by ref - if you are looking at the language definition you are correct. However I don't think there is an implementation that actually creates a copy of the string because it would be incredibly slow. Also since strings are immutable primitives there is no need to copy them since they can't change.