If I open JS console and write:
let foo;
and after:
let foo = "bar"
console show me (rightly)
Uncaught SyntaxError: Identifier 'foo' has already been declared
Now... sometimes I need to inject my code inside an existing script and I don't have tool to determinate if a let variable is already defined.
I try with this code, but there is evident problem with JS scope and logic.... (comment the code)
let foo; // Gloabl variable empty declare in a code far, far away
console.log(foo); // undefined
console.log(typeof foo === "undefined"); // test that determinate if condition is true
if(typeof foo === "undefined"){
let foo = "test";
console.log(foo); // return "test" this means that foo as a local scope only inside this if...
}
console.log(foo); // return undefined not test!
// and .. if I try to double declaration...
let foo = "bar"; //error!
so... How can I prevent double "let" declaration? / How to determinate if a let var is defined (declared?)
P.S with "var" all working fine!!!
You can define a scope for your script. You still have access to external variable inside that scope.
let toto = 42;
let foo = "bar";
console.log(toto);
//Some added script
{
let toto = "hello world !";
console.log(toto);
console.log(foo);
}
//back to main script
console.log(toto);
You still can programmatically check if a variable exists or not using try - catch
but this can be very tricky to declare a variable inside of try { } catch { }
scopes
let existingVariable = "I'm alive !";
try
{
console.log("existingVariable exists and contains : " + existingVariable);
console.log("UndeclaredVariable exists and contains : " + UndeclaredVariable);
}
catch (ex)
{
if (ex instanceof ReferenceError)
{
console.log("Not good but I caught exception : " + ex);
}
}
console.log("Looks like my script didn't crash :)");
If you don't want to create a new scope to make sure your variables don't already exist in the existing script, well... prefix them let r1sivar_userinput
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With