Global Variables
While string primitives are not passed by reference, one option not mentioned is the ability to use global variables. Of my own conscience, I must advise against this, but not knowing your use case you should know of your options:
s = 'a' // created as a global variable
appendSeparating('b', '|') // function now takes only two arguments
console.log(s) // global variable affected
function appendSeparating(s2, separator) {
// s is a global variable
if (typeof s === 'undefined')
return;
if (s != "")
s += separator;
s += s2;
}
Return Assignment
Of course you could build your own function and use the return variable as an assignment. Below I've used a prototype function, but should also advise against this, without fully understanding the implications (experience can take years) — you may see that I'm teaching you what not to do:
String.prototype.append = function(str, delimiter) {
return [this, str].filter(v => v !== '').join(delimiter || '|')
};
let ex1 = 'a'
ex1 = ex1.append('b')
console.log('no delim: ', ex1)
let ex2 = 'a'
ex2 = ex2.append('b', '-')
console.log('w/ delim: ', ex2)
Here's a "better" way to do the same. Although efficient, the untrained eye might struggle to understand what is occurring in the body of the function. It's subjective, but for maintainability you might want to make something more readable:
let ex1 = 'a'
ex1 = append(ex1, 'b')
console.log('no delim: ', ex1)
let ex2 = 'a'
ex2 = append(ex2, 'b', '-')
console.log('w/ delim: ', ex2)
function append(prefix, suffix, delimiter) {
return [prefix, suffix].filter(v => v !== '').join(delimiter || '|')
};
Object Mutation / Scoping
The final thing you can do is modify an object. Not only will this get close to what it seems you'd like, but in larger applications is very nice to scope variables in objects to avoid collision and ease debugging (though, at the cost of a performance penalty):
const strings = {}
// Assuming key name
strings.s = 'foo'
append(strings, 'bar', ': ')
console.log(strings.s)
// Supplying key name
strings.x = 'x'
appendNamed(strings, 'x', 'y')
console.log(strings.x)
function append(str, suffix, delimiter) {
str.s = [str.s, suffix].filter(v => v !== '').join(delimiter || '|')
};
function appendNamed(str, strName, suffix, delimiter){
str[strName] = [str[strName], suffix].filter(v => v !== '').join(delimiter || '|')
};