This question already has answers here: JavaScript closure inside loops – simple practical example (44 answers)