Changing the scope of "let" declaration

783 Views Asked by At

I want to run a script multiple time, and I don't know whether it's first run or not - so I have to ask, and if so, I'll declare it:

if (typeof variable == undefined) { let variable = new Set(); }

Unfortunately 1.) re-declaring with let variable; all the time throws an error 2.) This variable is live only in the "if" scope 3.) Command "let" require a full block if, ternary or "braclet-less if" throws an error

Can I change the scope of the variable? Just like the good-old var - I have no problem with that, I just want to use Set (and also a good lecture to know whether it's possible or not) Maybe some "declare if not declared" command?

2

There are 2 best solutions below

3
paroxyzm On BEST ANSWER

I'm, not sure what are you trying to do exactly. Is the code run in the browser?

If so, you can try and omit var/let/const keywords:

if (typeof variable == undefined)  { variable = new Set(); }

This will create a variable in the window object if it doesn't exist

[EDIT]: Of course, you can make it "better" by being explicit about the object where the global variable comes from.

for browsers this code would become:

if (typeof window.variable == undefined)  { window.variable = new Set(); }

If you are working in a team this solution is better, but if you're just starting out or trying to learn, both are fine.

2
Kamran Khatti On

You can simply declare variable first then do operations on it.

let variable; // declare variable 

if (typeof variable === 'undefined') { variable = new Set(); }

It should not throw any of the error you mentioned.