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
CodePudding user response:
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)
}
CodePudding user response:
Before printing to the console, the code does this: i
, which increments i
. Then, the code prints the value of i
, which is now 1.