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;
};
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
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