Donald Zhu
Donald Zhu

Reputation: 855

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

Upvotes: 4

Views: 3526

Answers (1)

o1sound
o1sound

Reputation: 500

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

Upvotes: 3

Related Questions