2

Where are constants created in a global scope stored in JavaScript?

For example, if I create a variable using: var var_example = '123', I can access it by window.var_example.

However, if I create a const variable using: const const_example = '456', then how do I access it?

I need this to create an immutable/read-only global variable in a function. I can create an ordinary global variable in a function using: window.in_function_var = 'global variable', but I don’t know how to create a constant/immutable/read-only global variable in a function; it seems to me that this can be done by accessing a scope with constants and adding the desired variable there.

Dharman
  • 30,962
  • 25
  • 85
  • 135
sopafoy
  • 33
  • 2
  • 2
    With regards to how you access a `const` variable - you do it as you normally would; by name within its scope. This seems to be an X/Y question. What is the actual issue you're trying to address? – Rory McCrossan Jan 16 '20 at 10:10

2 Answers2

2

Variables declared using the const and let not defined on window because the specification says so.


You could use Object.defineProperty() to add a property to the window object. This will set writable: false and configurable: false by default

Object.defineProperty(window, "in_function_var", {
  value: 'global variable'
})

console.log(in_function_var)

in_function_var = "updated"
console.log(in_function_var)

delete window.in_function_var
console.log(in_function_var)

In strict mode, it throws an error if you try to update or delete the property:

"use strict"

Object.defineProperty(window, "global_var", {
  value: 'global variable'
})

try {
  global_var = "updated"
} catch (e) {
  console.error(e)
}

try {
  delete window.global_var
} catch (e) {
  console.error(e)
}
adiga
  • 34,372
  • 9
  • 61
  • 83
  • Thanks, both answers helped a lot. I'd like to clarify if I can somehow redefine a function variable with this method. When variable is declared using function example_var() {} then example_var cannot be redefined by defineProperty. – sopafoy Jan 16 '20 at 21:52
  • @sopafoy just set the `value` to that function function: `Object.defineProperty(window, "example_var", { value: function example_var() { ... } })` – adiga Jan 17 '20 at 07:57
2

You can try to define an immutable property for window object. But this is not the same as a constant. It will not be possible to change it, but there will be no same error when trying to change.

"use strict"
const CONST1 = 1;

function setGlobalConst() {
  Object.defineProperty(window, "CONST2", {
      enumerable: false,
      configurable: false,
      writable: false,
      value: 2
  });
};

setGlobalConst();

console.log("CONST1: " + CONST1);
console.log("CONST2: " + CONST2);

// no have error but not mutted
CONST2 = 3;
// error
CONST1 = 2;