Is it bad practice to use the same variable name in multiple for-loops?

后端 未结 6 1278
一个人的身影
一个人的身影 2021-02-01 12:20

I was just linting some JavaScript code using JSHint. In the code I have two for-loops both used like this:

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


        
6条回答
  •  别那么骄傲
    2021-02-01 12:59

    It has been mentioned only in the comment by @TSCrowder: If your environment supports it (Firefox, Node.js), in ES6 you can use let declaration

    //for-loop 1
    for (let i = 0; ...; i++) { ... }
    
    //for-loop 2
    for (let i = 0; ...; i++) { ... }
    

    which limits the scope to within the for-loop. Bonus: JSHint stops complaining.

提交回复
热议问题