Search code examples
javascriptpostfix-operator

Postfix operator in JavaScript


This is a basic JS question I think, but I just couldn't find an answer that I was satisfied with. I'm learning operators in JavaScript and I can't understand this following postfix example and how it works:

var x = 4;
var y = x++;

For example, when I alert x, it gives me 5. But when I alert y, it gives me 4. And I can't understand the logic behind it. I understand that, because it's a postfix, x is assigned to y. And y reads just x, without the postfix. But why does then the original x read the postfix instead if I'm applying it to a different var?

If I just did var y = x + 1, the original x would stay unchanged. But that's not the case when I use postfix. Why would I even change the x with this method? Couldn't I just go then var x = 4; x++; ? And not bother changing it via another var?

I apologize if this is too basic and thanks in advance!


Solution

  • It's easier to think of the increment operators as little functions that return something. So x++ is a functions that increments x and returns the original value of x, whereas ++x does the same thing but returns the new value.

    This comes in handy from time to time especially in loops where you want precise control of the stopping point. For example, compare:

    let i = 0, j = 0;
    
    while (++i < 5) {
        console.log(i) // stops at 4
    }
    
    while (j++ < 5) {
        console.log(j) // stops at 5
    }

    The difference is because the while loop evaluates one before the increment and the other after.

    Similarly in recursive functions you'll often see things like:

    function recurse(i) {
        if (i == 5) return i
        console.log(i)
        return recurse(++i)
    }
    console.log("final: ", recurse(0))

    But if you use the postfix return recurse(i++) you get infinite recursion.