Search code examples
javascriptvariablesclosurescapture

Javascript - Access variable in function closure from outside


I was wondering if there was some way to obtain the value of a variable that has been captured by a nested function, from outside of that said function. A little tricky to explain in words so here's what I'm trying to achieve:

function counter(){
    let count = 0;
    return function counterIncrementer(){
      ++count;
    }
}

function someReceiever(counterIncrementer){
    // From here, somehow access the value of count captured by 
    // counterIncrementer.
    // -> Without modifying the counter/returned counterIncrementer function 
    //    before runtime
}
someReceiever(counter())

Thanks !


Solution

  • The only way to do this would be to declare count as a global, or create another function just for accessing count, nested within counter; but given the structure of your code, it doesn't seem like that's a great answer.

    function counter(){
        let count = 0;
        return [
            function counterIncrementer(){
                ++count;
            }, 
            function counterGetter() {
                return count;
            }
        ];
    }
    
    function someReceiever(counterIncrementerPack){
        let counterIncrementer = counterIncrementerPack[0];
        let counterGetter = counterIncrementerPack[1];
    
        console.log(counterIncrementer(), counterGetter(), counterGetter(), counterIncrementer(), counterGetter());
    }
    someReceiever(counter())
    

    Outputs: undefined 1 1 undefined 2

    Note: you may also want to make counterIncrementer return ++count, but that wasn't the question shrug.