Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string as parameter by reference

I want to alter the contents of a string in a function, for example

function appendSeparating(s, s2, separator) {
    if (s != "")
        s += separator;
    s += s2;
}

I'd like to have s altered on return but as string is a primitive is being passed by value so the modifications do not affect the original.

What is the most efficient/clean way to deal with this? (I try to keep code concise)

like image 691
tru7 Avatar asked Dec 24 '22 09:12

tru7


1 Answers

JavaScript has no out parameters if that's what you mean. The simplest way of dealing with this is to pass the string in an object.

function appendSeparating(stringObj, s2, separator) {
    if (stringObj.text != "")
        stringObj.text += separator;
    stringObj.text += s2;
}
like image 89
Aron Avatar answered Jan 12 '23 18:01

Aron