r/programming • • Aug 30 '15

JavaScript “maze generator” in a tweet

https://twitter.com/botond_balazs/status/637960240055615488
841 Upvotes

177 comments sorted by

View all comments

Show parent comment

18

u/mozjag Aug 30 '15
> for (i = 4000; --i;) { console.log(i) }
3999
3998
3997
…
3
2
1

> for (i = 4000; i--;) { console.log(i) }
3999
3998
3997
…
3
2
1
0

If you look at the output of your code you'll notice the character in the bottom right of the maze is missing. If I change the --i to i-- I get that character in the bottom right and no line break before the first line.

In both cases i goes from 3999 downwards in the body of the for-loop since the decrement happens as part of the test and therefore before execution of the body, so you can't get into the situation where 4000 % 80 results in an empty line before the maze. The difference is that for --i the new value of i is tested for false-ness where for i-- the old value is tested, so if i is 1, in the --i case you test 0 for false-ness and skip the body, effectively looping from 3999 to 1 inclusive, where in the i-- case you test 1 for false-ness and execute the body, effectively looping from 3999 to 0 inclusive.