Search code examples
javascriptglobal-variableses6-modules

Are immutable globalThis variables possible in JS?


Is there a way to make

globalThis.variable = value

const, final, readonly...?

It would make sense to have global cross-modules variables that are readonly. Of course manually exporting variables makes them immutable in other modules, but it's not the same luxury as just having global variables (that I can just call anywhere, without having to import everywhere).


Solution

  • You can use defineProperty with writable: false:

    Object.defineProperty(globalThis, 'variable', {
      value,
      writable: false,
    });
    

    Examples:

    Silently ignores without "use strict";

    Object.defineProperty(globalThis, 'variable', {
      value: 123,
      writable: false,
    });
    
    console.log(variable);
    variable = 567;
    console.log(variable);

    Error with "use strict";

    "use strict";
    
    Object.defineProperty(globalThis, 'variable', {
      value: 123,
      writable: false,
    });
    
    console.log(variable);
    variable = 567;
    console.log(variable);