Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a block variable in Javascript set by "let"?

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;
};
like image 517
Donald Zhu Avatar asked Oct 20 '25 04:10

Donald Zhu


1 Answers

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
like image 193
o1sound Avatar answered Oct 22 '25 18:10

o1sound