How To Update A Destructured JavaScript Variable Based On Scopes/Closures?
The following code below is a destructuredcount variable and increaseCount updater function.
How can I update the value of the count variable anytime I execute the increaseCount function?
Is this even possible?
Note: I do not want the count variable to be a Global variable.
From the code below I tried using Closures to solve the problem. But 1 is still displayed even after the second console.log.
function getCount() {
let _count = 1;
const _updateCount = () => {
_count = _count + 1;
};
return [_count, _updateCount];
}
const [count, updateCount] = getCount();
console.log(count); /* <===== Expect initial count to be 1 */
updateCount();
console.log(count); /* <===== After calling updateCount I Expect count to be 2 */
I Expect count to be 1 when the firstconsole.log is called.
When updateCount is called I expect the count variable to be updated to 2.
Therefore when the second console.log is called I expect 2 to be displayed.
Answer
Given your current code, it's not possible if you want to be able to call getCount
more than once - you destructured count
, a primitive on the top level. The only way to change it would be to reassign the outer variable inside getCount
, which is a bad idea.
let count;
function getCount() {
count = 1;
const _updateCount = () => {
count = count + 1;
};
return _updateCount;
}
const updateCount = getCount();
console.log(count); /* <===== Expect initial count to be 1 */
updateCount();
console.log(count); /* <===== After calling updateCount I Expect count to be 2 */
An easy fix would be not to put a primitive in the first spot in the array, but instead use a function which returns the inside _count
:
function getCount() {
let _count = 1;
const _updateCount = () => {
_count = _count + 1;
};
return [() => _count, _updateCount];
}
const [getInternalCount, updateCount] = getCount();
console.log(getInternalCount()); /* <===== Expect initial count to be 1 */
updateCount();
console.log(getInternalCount()); /* <===== After calling updateCount I Expect count to be 2 */
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