Search code examples
javascriptwhile-loopincrement

Postfix Increment in While Loop Javascript


Could anybody explain to me please why this loop

let i = 0
while (i < 5) {
    i++
    console.log(i)  
}

shows 1,2,3,4,5 ?

As I know postfix increment returns the old value, right? so first shouldn't it log 0 into the console?

Thank you


Solution

  • That is true, when executing as one statement. You have separated it in 2 lines, so 2 statements, each one is executed sequentially


    The following code would do it

    let i = 0
    while (i < 5) {
        console.log(i++)  
    }
    console.log("===============")
    i = 0
    while (i < 5) {
        a = i++
        console.log(a)  
    }


    Whereas the prefix increment does 12345

    let i = 0
    while (i < 5) {
        console.log(++i)  
    }
    console.log("===============")
    i = 0
    while (i < 5) {
        a = ++i
        console.log(a)  
    }