Categories
JavaScript Answers

How to Fix the ‘Duplicate Declaration‘ Warning for Loop Variables with JavaScript?

Spread the love

Sometimes, we may run into the ‘duplicate declaration‘ warning for loop variables with JavaScript.

In this article, we’ll look at how to fix the ‘duplicate declaration‘ warning for loop variables with JavaScript.

Fix the ‘Duplicate Declaration‘ Warning for Loop Variables with JavaScript

To fix the ‘duplicate declaration‘ warning for loop variables with JavaScript, we should make sure we use let instead of var to declare our loop variables.

For instance, instead of writing:

for (var i = 0; i < 100; i++) {
  // ...
}

for (var i = 0; i < 500; i++) {
  // ...
}

where the i variable from both loops are hoisted to the top and so they’re counted as duplicate declarations, we write:

for (let i = 0; i < 100; i++) {
  // ...
}

for (let i = 0; i < 500; i++) {
  // ...
}

Then we declare i for both loop blocks.

Since let is block-scoped, they’re considered separate variable declarations.

Conclusion

To fix the ‘duplicate declaration‘ warning for loop variables with JavaScript, we should make sure we use let instead of var to declare our loop variables.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *