Recent Entries 3
- snippet tip 120d agoUse JavaScript for loops if you need to break out earlyThe usefulness of the humble `for` loop in modern JavaScript is rarely talked about. Apart from it being particularly useful in [asynchronous operation scenarios](/js/s/async-array-loops), it can also make your code a lot more performant shall you need to break out of a loop early. Consider the following example: Obviously, the code isn't optimized, but it highlights the issue of array methods, such as `Array.prototype.forEach()` being unable to break out of the loop early. To counteract this, we could use a `for` loop and an early `return` instead:
- gotcha major 124d agoDefer in a loop does not execute until the function returnsPlacing defer inside a for loop defers the call until the enclosing function returns, not until the end of each loop iteration. Files or locks acquired in the loop body are held for the entire function lifetime.
- gotcha major 125d agoClosure variable in for loop captures final valueUsing var in a for loop and referencing the variable in a closure (setTimeout, event handler) captures the same variable — all closures see the final value. Classic interview question.