0

Is what I’m trying to accomplish possible? I hear using globalThis is the best alternative to window, frames, etc. but I can’t get it to function. Any help would be appreciated!

var x = true;
var y = true;

function makeFalse(changeVar) {
  globalThis.changeVar = false;
}

makeFalse("x");
makeFalse("y");

console.log(x); //expecting: false, returning: true
console.log(y); //expecting: false, returning: true
  • 3
    It’s possible (with brackets instead of a dot), but it’s not a good idea. (Even `var` itself is dated, and if you change the `var`s to `let`s, `x` and `y` will stop being properties of the global object.) What are you going to use this ability for? – Ry- Nov 29 '21 at 06:51
  • Related: ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530) and [Use dynamic variable names in JavaScript](https://stackoverflow.com/q/5117127) – VLAZ Nov 29 '21 at 06:57

1 Answers1

0

You can update them using global window object or with this or with globalThis inside the function.

this and globalThis inside makeFalse function refers to global window object itself.

var x = true;
var y = true;

function makeFalse(changeVar) {
  // window[changeVar] = false;
  // this[changeVar] = false;
  globalThis[changeVar] = false;
}

makeFalse("x");
makeFalse("y");

console.log(x); //expecting: false, returning: true
console.log(y);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49