jsejcksn jsejcksn - 1 year ago 95
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!';


I realize that it won't modify
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
to an object or array to hold my string instead of a primitive?

Answer Source

Instead of a global variable, use an object.

let wish = {
  msg: 'Happy birthday!'

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download