Reputation: 165
I want to do something like this:
function defineGlobalConst(){
const s = 10;
}
but I would like to access variable s from anywhere in my code, as I didn't type "const"
Upvotes: 1
Views: 1195
Reputation: 3711
You can define a global variable like this:
In a browser:
function defineGlobalConst(){
window.s = 10;
}
In node:
function defineGlobalConst(){
global.s = 10;
}
If you want it to be a constant you could use defineProperty and a getter:
Object.defineProperty(window, "s", {
get: () => 10,
set: () => { throw TypeError('Assignment to constant variable.') },
});
Upvotes: 9
Reputation: 2408
Your only option is to store the value in the window. Just be sure to at least namespace your value, as it could conflict with something else already in the window:
// Create the namespace at the beginning of your program.
if (!window.MY_APP) {
window.MY_APP = {};
}
window.MY_APP.s = 10;
Upvotes: 1
Reputation: 65808
It is possible to solve your problem by utilizing an anti-pattern. Be advised that I'm not advocating this approach, but from a pure "can you do it" perspective, any non-declared variable that is assigned in a function becomes a Global by default (of course this does not create a constant as you've asked, but thought I would show it anyway):
function foo(){
bar = "baz"; // implicit Global;
}
foo();
// Show that "bar" was, in fact added to "window"
console.log(window.bar); // "baz"
console.log(bar); // "baz"
Upvotes: -2