Closure explanation

why does the fist return 0 and the other -1. I expected the first one to also return -1

function closure (){
    let count = 0
    return function minus () {
        return  count --
        
    }
}


let answer = closure()


console.log(answer())
// 0
function closure (){
    let count = 0
    return function minus () {
       count --
        return  count 
        
    }
}


let answer = closure()


console.log(answer())
// -1

The count-- returns its value, and then does the decrement. If you’d done return --count, you’d get the result you expect.

1 Like

i find that strange, if possible could you explain why for example, this returns 36, is it doing something different?

function closure (){
    let count = 6
    return function minus () {
        return   count * 6
        
    }
}


let answer = closure()


console.log(answer())

That would be like doing return count - 1. Evaluating the result (the value) and returning it.

As mentioned. The decrement operator can be used as postfix or prefix.

Decrement (–)

If used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.

If used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing.

1 Like

when you say That would be like doing return count - 1 . Evaluating the result (the value) and returning it. im reading that and thinking yes so count = 0 so count - 1 = count (0) -1 so the answer should be -1. there must be a mistake in how I am thinking about that. could you elaborate on - evaulating the result(the value) please

seems very odd that if you have a function like this

let count = 10
function decrease () {
    
    return count --
}


console.log(decrease())

it doesnt really do anything, just returns the original value

--count will decrement count then return the decremented value

count-- will return the value of count then decrement it

It does do something, it decrements the value of count by one

1 Like

what I meant was, is there someway you could you then use the decremented value ? from my view it returns the original value and then function exits so decrementing after the return does not seem useful or is there a good use for that ?

Sure, you can just use count, not the return value of the function. But it’s just an example – if you use the postfix version of decrement, then the current value gets returned, and doing it like this makes it explicit – that’s all it is.

1 Like

got it thanks everyone!

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.