Ad
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;
};
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad