Demystifying 'const' in For Loops: Traditional vs. for...of
Mohamed Idris
Posted on November 27, 2023
In JavaScript, the use of 'const' in for loops can be a source of confusion. Let's explore why 'const i' throws an error in a traditional for loop but works seamlessly in a for...of loop.
Traditional For Loop:
In a traditional for loop, declaring a loop variable with 'const' creates a constant that cannot be reassigned. Since the nature of the loop involves incrementing the loop variable ('i'), attempting to modify it with 'i++' violates the 'const' rule, resulting in an error: Uncaught TypeError: Assignment to constant variable.
For...of Loop:
In a for...of loop, the story unfolds differently. Here, 'const' is used to create a new constant variable ('element') for each iteration. It holds the current element's value and is valid because we're not attempting to reassign 'element.' The 'const' ensures that 'element' retains its value throughout the loop without allowing reassignments.
Why Does This Matter?
Predictable Code: Using 'const' in for...of loops ensures that the loop variable won't be accidentally modified within the loop, making the code predictable and easy to understand.
Traditional Loops: In traditional for loops, 'let' or 'var' is required when a mutable loop variable is needed, allowing reassignment throughout the loop iterations.
Understanding the subtleties of 'const' in different loop contexts empowers us to write cleaner, error-free, and more maintainable JavaScript code.
Posted on November 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.