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

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

    Variables in javascript are function scoped (not block scoped).

    When you define var i in a loop, it remains there in loop and also in the function having that loop.

    See below,

    function myfun() {
        //for-loop 1
        for (var i = 0; ...; i++) { ... }
    
        // i is already defined, its scope is visible outside of the loop1.
        // so you should do something like this in second loop.
    
        for (i = 0; ...; j++) { ... }
    
        // But doing such will be inappropriate, as you will need to remember
        // if `i` has been defined already or not. If not, the `i` would be global variable.
    }
    

提交回复
热议问题