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

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

    I know this question has been answered, but if you want super for loops, write them like this:

    var names = ['alex','john','paul','nemo'],
        name = '',
        idx = 0,
        len = names.length;
    
    for(;idx

    A couple of things going on here...

    1. The array length is being stored in len. This stops JS evaluating names.length every iteration

    2. The idx increment is a PRE-INCREMENT (e.g. ++idx NOT idx++). Pre-increments are natively faster than Post-increments.

    3. The storing of a reference to name. This is optional but recommended if you'll be using the name variable a lot. Every call to names[idx] requires finding the index in the array. Whether this search be a linear search, tree search or hash table, the find is still happening. So store a reference in another variable to reduce lookups.

    Finally, this is just my personal preference, and I have no proof or any performance benefits. However I always like initialising variables to the type they're going to be e.g. name = '',.

提交回复
热议问题