Ad

How To Change A Block Variable In Javascript Set By "let"?

- 1 answer

If I declared a variable at the top of a Javascript file like:

let x = 3;

How can I change it in a function later? I know you can use window.x with variables set by var, but how do you change it if it was declared by let?

let x = 3;

function myFunction(){
   x = 4;
};
Ad

Answer

You have set a global variable x. It is available globally. Your function changes that global variable to 4. Simple as that.

let x = 3;

function myFunction(){
   x = 4;
};
console.log(x) // 4

To perhaps expand on this, what if you were to re-declare x inside myFunction()? That would shadow the global x you declared at the top. Global x would still be 3 even after you ran the code, but x would be 4 inside the function.

let x = 3;

function myFunction(){
    let x = 4; // this will now shadow the global x at the top
    console.log(x);
};
console.log(x) // 3

And if you were to run myFunction()...

myFunction(); // 4
Ad
source: stackoverflow.com
Ad