Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How to prevent let double declaration? / determine if let variable is defined

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!!!

like image 810
r1si Avatar asked Sep 12 '18 09:09

r1si


Video Answer


1 Answers

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

like image 56
Cid Avatar answered Sep 23 '22 02:09

Cid