1

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?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
user33276346
  • 1,501
  • 1
  • 19
  • 38
  • You will have to reference the window object inside tada or pass the window object into tada. – evolutionxbox Feb 23 '21 at 12:48
  • 1
    Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – evolutionxbox Feb 23 '21 at 12:49

2 Answers2

2

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;
}
Thomas
  • 174,939
  • 50
  • 355
  • 478
-1

Your window.nada is a primitive data type (Boolean).

Primitive data types are passed to the function per value and not per reference. So inside your tata function the lala variable does not know anything about the window.nada value

yunzen
  • 32,854
  • 11
  • 73
  • 106
  • Even if it were an object; simply assigning to `lala` won't change anything in the `window` object. It just changes `lala` to refer to a different object. – Thomas Feb 23 '21 at 12:50