Use let instead of var so each iteration gets a fresh binding, or wrap the body in an IIFE that captures the current value of i as a parameter.
Common Function Bugs in JavaScript and How to Fix Them
How do you fix the closure loop bug with var and setTimeout?
The answer
More FAQs in Common Function Bugs in JavaScript and How to Fix Them
Because the method is detached from obj when passed as a reference. setTimeout calls it with this as the global object (or undefined in strict mode). Fix it with .bind(obj), an arrow wrapper, or () => obj.method().
Because the braces are interpreted as a block body, and the object literal looks like a label statement. Wrapping the object in parentheses (n) => ({ x: 1 }) makes it an expression body that returns the object.
Because arrays are passed by reference. Mutating the parameter mutates the same object the caller holds. Copy the array ([...list]) before mutating if you want to preserve the original.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.