0

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?

jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • setting an object is probably the best way to go because global vars are frowned upon, but if you wants to do it with vars and the answer to you exact solution is my answer. – wordSmith Oct 25 '16 at 21:44
  • 1
    `eval` would work but isn't really a solution. – Bergi Oct 25 '16 at 22:25

2 Answers2

1

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);
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
-1
let wish = 'Happy birthday!';

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

translate(wish);
console.log(wish); //Alles Gute zum Geburtstag!

You don't have to use the return, but global variables can be set form anywhere where there isn't a var by the same name in a lesser scope.

wordSmith
  • 2,993
  • 8
  • 29
  • 50
  • I realize that I can statically reference the variable in the function, but that defeats the purpose of the function. – jsejcksn Oct 25 '16 at 21:43
  • @jsejcksn The point of a function is to to use less memory at the cost of more cycles. So as long as you use the function more than once, it doesn't defeat the purpose of the function. If you're only using it once then don't use a function. – wordSmith Oct 25 '16 at 21:46
  • I think the wording of my question might not be clear. I'll think about it some more. – jsejcksn Oct 25 '16 at 21:47