languages/why-does-my-javascript-loop-run-one-time-too-many.md

Why does my JavaScript loop run one time too many?

Programming languages · 8 min read ·

A loop tells JavaScript to repeat some code until a condition says stop. A for loop packs three pieces onto one line: a setup that runs once, a condition checked before every lap, and an update that runs after every lap.

Step through for and while loops to watch the counter change on each lap, then play with start, end, step and the < vs <= switch. Along the way you'll see where the classic off-by-one bug comes from, and the one-character fix.

$ ls languages/

see all →
languages/javascript-closures-how-a-function-remembers-a-variable-after-the-func.md JavaScript closures: how a function remembers a variable after the function that made it has finished A function in JavaScript can still use a variable long after the function that created it has finished. That is called a closure, and you… 5 min read · 3 Nov languages/ruby-blocks-how-a-method-borrows-a-piece-of-your-code-and-runs-it-with.md Ruby blocks: how a method borrows a piece of your code and runs it with yield Ruby code is full of curly-brace chunks like `list.each { |x| ... }`. Who runs that chunk, and when? This article follows a block from the… 4 min read · 31 Oct languages/reference-counting-how-python-knows-when-to-throw-an-object-away.md Reference counting: how Python knows when to throw an object away You never tell Python to free memory, yet unused objects disappear. How does it know when one is finished with? CPython keeps a tally on… 5 min read · 28 Oct languages/generators-how-a-python-function-can-pause-in-the-middle-and-pick-up-w.md Generators: how a Python function can pause in the middle and pick up where it left off A generator is a Python function that can pause halfway, hand you a value, and carry on later from the same line with its variables intact… 4 min read · 25 Oct languages/javascript-s-event-loop-why-settimeout-0-runs-after-the-code-below-it.md JavaScript's event loop: why setTimeout(…, 0) runs after the code below it Why does `setTimeout(fn, 0)` run after the lines below it, and why does a promise callback beat it? JavaScript has one worker and two… 5 min read · 22 Oct languages/rust-ownership-why-let-b-a-makes-a-unusable.md Rust ownership: why let b = a makes a unusable Why does Rust refuse to compile `let b = a;` followed by a use of `a`? Because of ownership: every value has exactly one owner, and… 5 min read · 19 Oct