Ad

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 */
  1. I Expect count to be 1 when the firstconsole.log is called.

  2. When updateCount is called I expect the count variable to be updated to 2.

  3. Therefore when the second console.log is called I expect 2 to be displayed.

Ad

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 */

Ad
source: stackoverflow.com
Ad