jsejcksn jsejcksn - 1 month ago 6
Javascript Question

Modify global variable inside function via parameter

Here is an example:



let wish = 'Happy birthday!';

function translate(msg) {
msg = 'Alles Gute zum Geburtstag!';
}

translate(wish);
console.log(wish);





I realize that it won't modify
wish
because JavaScript is "pass by value" and not "pass by reference", so how can I modify that variable (which is outside of the function) by passing a value to the function? Is it impossible without changing
wish
to an object or array to hold my string instead of a primitive?

Answer

Instead of a global variable, use an object.

let wish = {
  msg: 'Happy birthday!'
};

function translate(obj) {
  obj.msg = 'Alles Gute zum Geburtstag!';
}

translate(wish);
console.log(wish.msg);