DEV Community

Mohamed Idris
Mohamed Idris

Posted on

1

Demystifying 'const' in For Loops: Traditional vs. for...of

Demystifying 'const' in For Loops: Traditional vs. for...ofIn 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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay