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

后端 未结 6 1280
一个人的身影
一个人的身影 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:52

    The best practice is to reduce the scope of variables, so the best way to declare iteration variable for the loops is

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

    I know the scope of the variables declared with var but I am taking about code readability here.

提交回复
热议问题