is it possible to throw your local variable out to globally so that you can reuse it?

e.g.

let x = 'a random string'

function test() {
let y = 'bzzz'
return y
}

let x = 'a random string'

function test() {
let y = 'bzzz'
return y
}
I want to use the 'y' variable globally, is that possible?
6 Replies
Jochem
Jochem2y ago
running let y = test(); in the global scope would be the best way generally it's a bad idea to implicitly change values in the global scope from inside a function, because a couple of weeks from now you might forget that you're doing that and that can cause bugs that are hellish to fix
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
ei
eiOP2y ago
I see, thanks for pointing that out
Jochem
Jochem2y ago
needing to do that is generally a good sign you need to refactor somethiing
MarkBoots
MarkBoots2y ago
I was thinking of this, and i think i would just use a clean object to store global variables (not really global, but it's organized )
const globals = { } //or what ever you want to name it

function test() {
globals.y = "foo";
}
test();
console.log(globals.y);
const globals = { } //or what ever you want to name it

function test() {
globals.y = "foo";
}
test();
console.log(globals.y);
Its a bit more chars, but its way more organized. And you don't have to worry about reserved names on window
ei
eiOP2y ago
yeah I think storing it inside an object makes it look cleaner, thanks!
Want results from more Discord servers?
Add your server