Why JavaScript Loops Log the Same Value and How 'let' Fixes It
A common JavaScript pitfall causes loops using setTimeout to print the same value repeatedly instead of sequential numbers. This happens because 'var' is function-scoped, meaning all iterations share a single variable that has already reached its final value by the time any callback executes. Replacing 'var' with 'let' resolves the issue, as 'let' is block-scoped and creates a fresh binding for each loop iteration. The bug is not limited to setTimeout and can appear with any deferred callback, including event listeners and promises. Understanding the scoping difference between 'var' and 'let' is key to diagnosing and preventing this entire category of bug.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in