Simple "while". Why it print 1 2 2 instead of 1 2?


#1

I don't know why this code will print: 1 2 2 to the console. I think this code should run like this:
First, n=1 (true), print 1 then n=2 (true) then print 2 then n=3 (false). So it must print 1 and 2 only

var n=1;
while(n<3) {
    console.log(n);
    n++;
}

#2

it is console behavior, if you would for example append to a webpage you would only see 1 and 2


#3

I paste this code on my browser (chrome) then it prints 1 2 2 :((


#4

like i said, console behavior. You can try to use ++n instead? Or just append it to html, so you can see it is indeed console behavior, don't worry about it, console is used for debugging


#5

thank you, I'm newbie


#6

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