Search code examples
javascriptpass-by-reference

Pass window variable as parameter in Javascript


Passing a window global variable through JS does not seem to be working. The following code is printing true:

window.nada = true;
tata(window.nada);
console.log(window.nada);

function tata(lala) {
  lala = false;
}

How can I affect the window.nada global variable inside the tata function?


Solution

  • Technically, JavaScript uses call-by-sharing.

    In practice, you'll have to pass the entire window object, as well as the name of the property you want to change:

    tata(window, 'nada');
    
    function tata(window, prop)
    {
      window[prop] = false;
    }