SitePoint Sponsor

User Tag List

Results 1 to 24 of 24

Hybrid View

  1. #1
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Multiple for same i or not ? best practise

    Hi,
    I've a doubt
    in a case like this:
    PHP Code:
    for(var 0array1Lengthi++){
    }
    for(var 
    0array2Lengthi++){
    }
    for(var 
    0array3Lengthi++){

    for best practise I should change the i name or not ?

  2. #2
    SitePoint Enthusiast
    Join Date
    May 2011
    Posts
    55
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi whisher,

    I suggest you should keep it like

    for(var i = 0; i < array1Length; i++){
    }
    for(var j = 0; j < array2Length; j++){
    }
    for(var k = 0; k < array3Length; k++){
    }

    by this way it will be easy for you to keep track of code
    PHP Programming Its more than just writing code

  3. #3
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,332
    Mentioned
    192 Post(s)
    Tagged
    4 Thread(s)
    I believe this is one of those areas that is 'personal taste'.
    There was a time when conservation of the resources (memory) was paramount and, in that case, reuse of variables was a way to minimize the overhead.
    That is no longer a consideration. Even with an interpreted language like Javascript, there are very few instances where the difference between creating a new [counter] variable and [re]using an existing one is even measurable!

    It does make the code more readable (and, hence, easier to debug) if you use variable names that are descriptive and distinctive.
    In that case, I would recommend something like this:

    Code:
    for(var people = 0; people < peopleArrayLength; people++){
    }
    for(var address = 0; address < addressArrayLength; address++){
    }
    for(var email = 0; email < emailArrayLength; email++){
    }
    Personally, especially for counters, I simply reuse the same - short named - variable everywhere. Either 'i', as you have here or 'x' or 'c' (for counter).
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Git is for EVERYONE
    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Just to add my 2c worth:

    I do the same as Thom.
    If I declare a throw-away variable, for example for a counter, I always call it i.

    If I nest for loops then I increment the variable accordingly.
    E.g.

    Code JavaScript:
    for(var i = 0; i < array1Length; i++){ 
    } 
    for(var i = 0; i < array2Length; i++){ 
    } 
    for(var i = 0; i < array3Length; i++){ 
    }

    But:

    Code JavaScript:
    for(var i = 0; i < array1Length; i++){ 
      for(var j = 0; j < array2Length; j++){ 
        for(var k = 0; k < array3Length; k++){ 
        }
      }
    }

    Not sure if that is best practise, but I cannot think of any reason (apart from readability, as Thom mentioned above) why it might be a bad thing.

  5. #5
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks everybody for the feedback.

  6. #6
    Just Blow It bronze trophy
    DaveMaxwell's Avatar
    Join Date
    Nov 1999
    Location
    Mechanicsburg, PA
    Posts
    7,264
    Mentioned
    115 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Pullo View Post
    Just to add my 2c worth:

    I do the same as Thom.
    If I declare a throw-away variable, for example for a counter, I always call it i.

    If I nest for loops then I increment the variable accordingly.
    E.g.

    Code JavaScript:
    for(var i = 0; i < array1Length; i++){ 
    } 
    for(var i = 0; i < array2Length; i++){ 
    } 
    for(var i = 0; i < array3Length; i++){ 
    }

    But:

    Code JavaScript:
    for(var i = 0; i < array1Length; i++){ 
      for(var j = 0; j < array2Length; j++){ 
        for(var k = 0; k < array3Length; k++){ 
        }
      }
    }

    Not sure if that is best practise, but I cannot think of any reason (apart from readability, as Thom mentioned above) why it might be a bad thing.
    Bad developer! Bad! Bad! Making extraneous loops where they are not necessary......that could also cause problems depending on what happens inside the loops - you could end up with different results.

    I would also agree with felgall and paul - declare the variable once and reuse it. Declaring it multiple times is a waste of resources (CPU/memory/time, etc). If you can reuse it, then by all means do so. This is one lesson that I WISH the educators of today would reintroduce - it's one of the things I learned early on (back in the mainframe days). Coding for speed and efficiency will usually end up with the most elegant solution.

    Edit:

    OK - I now see why you did what you did - his question and his code pattern didn't match. The OP asked about nested loops, but the code in question isn't nested....
    Dave Maxwell - Manage Your Site Team Leader
    My favorite YouTube Video! | Star Wars, Dr Suess Style
    Learn how to be ready for The Forums' Move to Discourse

  7. #7
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by DaveMaxwell View Post
    Bad developer! Bad! Bad!
    Bang to rights!

    Quote Originally Posted by DaveMaxwell View Post
    I would also agree with felgall and paul - declare the variable once and reuse it. Declaring it multiple times is a waste of resources (CPU/memory/time, etc). If you can reuse it, then by all means do so. This is one lesson that I WISH the educators of today would reintroduce.
    Man, the kids today with their quad-core, hyperthreading i7 processors and their 20GB of Corsair DDR3 RAM!
    I just want to go back to the good old days of huge mainframes with 2000+ vacuum tubes.
    Days when micro-optimization made a difference!


    Quote Originally Posted by DaveMaxwell View Post
    Coding for speed and efficiency will usually end up with the most elegant solution.
    On a serious note, this is very true.

    Quote Originally Posted by DaveMaxwell View Post
    Edit:

    OK - I now see why you did what you did - his question and his code pattern didn't match. The OP asked about nested loops, but the code in question isn't nested....
    Just out of interest, you're not saying that there's anything wrong with nested for loops, are you?

  8. #8
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,278
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by ralph
    As an aside, I was watching Crockford yesterday lampoon the use of i++ instead of i += 1.
    Yeah because like Guido, he thinks we're somehow capable of reading complicated code but will fall into fits of confusion if someone does i++. I honestly don't understand the thinking there, and I strongly miss my i++/i-- in Python.

    Quote Originally Posted by ralph
    Anyhow, I've been learning about the different ways to invoke functions, and am surprised at how many ways there are to call functions...
    I like the plus because it looks funky:
    +function(){foobarbaz;}();

    http://jsperf.com/self-invoking-function

    Quote Originally Posted by paul wilkins
    My first thought about that is "is there a special reason why you're iterating over it in reverse order?"
    Closely followed by "Is he wanting to optimising for speed? What is it in this loop that has such a high demand?"
    Most often followed up by "Oh, the code doesn't need such performance enhancements. He's doing this instead to demonstrate that he knows about such techniques."
    Backwards is great when you're screwing with the array as you go, like, deleting stuff. That way, your index number doesn't change for the remaining items.

    Quote Originally Posted by pullo
    Just out of interest, you're not saying that there's anything wrong with nested for loops, are you?
    Well, I heard John Resig say JS finally has list comprehensions as stolen from Python, which means you don't necessarily have to have nested for loops (but in Python, the compiler is optimised for them so they're almost always a better choice than actual nested for loops, unless you think readability is an issue).

    pseudo:
    Code:
    for(var i = 0; i < array1Length; i++){
      if (array1[i].has-a.Foo) { 
          for(var j = 0; j < array2Length; j++){ 
         }
      }
    }
    
    becomes
    [j for i in array1 if Foo in i for j in array2]
    i think.


    I wouldn't mind having these available for my (non-nested) for loops, since often in my non-libraried JS I'm making throwaway loops all the time to separate out some DOM elements or whatever.

  9. #9
    Just Blow It bronze trophy
    DaveMaxwell's Avatar
    Join Date
    Nov 1999
    Location
    Mechanicsburg, PA
    Posts
    7,264
    Mentioned
    115 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Pullo View Post
    Man, the kids today with their quad-core, hyperthreading i7 processors and their 20GB of Corsair DDR3 RAM!
    I just want to go back to the good old days of huge mainframes with 2000+ vacuum tubes.
    Days when micro-optimization made a difference!



    On a serious note, this is very true.
    I know you were joking, but it's amazing how convoluted I see things nowadays - and how people are so amazed that just simplifying the logic makes the app work faster.....the copy/paste method of developing *sigh*

    Quote Originally Posted by Pullo View Post
    Just out of interest, you're not saying that there's anything wrong with nested for loops, are you?
    Nope, not at all. There's nothing wrong with them at all.

    The reason why I replied was I noticed your code would create a different result than his sample. His sample had three distinct loops, which ran separately - yours were nested.

    his:
    Code:
    for(var i = 0; i < array1Length; i++){   echo("i = " & i);}
    for(var i = 0; i < array1Length; i++){   echo("i = " & i);}
    
    for(var i = 0; i < array1Length; i++){   echo("i = " & i);
    }


    Yours
    Code:
    for(var i = 0; i < array1Length; i++){   for(var j = 0; j < array2Length; j++){     for(var k = 0; k < array3Length; k++){        echo("k = " & k);    }  }}
    Results would be totally different - but then I noticed his original post, which could be read to be asking about nesting the loops, which your answer would work for.
    Dave Maxwell - Manage Your Site Team Leader
    My favorite YouTube Video! | Star Wars, Dr Suess Style
    Learn how to be ready for The Forums' Move to Discourse

  10. #10
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,813
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    If you move all the variable declarations to the top of their scope then you will not have the var being repeated multiple times in the code unnecessarily. For example:

    Code:
    (function() {"use strict";
    var i, array1Length, array2Length, array3Length;
    
    ....
    
    for(i = 0; i < array1Length; i++){ 
    } 
    for(i = 0; i < array2Length; i++){ 
    } 
    for(i = 0; i < array3Length; i++){ 
    }  
    
    ....
    
    })();
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  11. #11
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,332
    Mentioned
    192 Post(s)
    Tagged
    4 Thread(s)
    One of my favorite patterns (especially in Javascript) is this:
    Code:
    var i = {length of array}
    while (i--) {
      //do something important with the array using the index 'i'
    }
    The only [perhaps undesirable] effect of this is that the array is iterated in reverse order. But the syntax is small and concise.
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Git is for EVERYONE
    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by ParkinT View Post
    One of my favorite patterns (especially in Javascript) is this:
    Code:
    var i = {length of array}
    while (i--) {
      //do something important with the array using the index 'i'
    }
    The only [perhaps undesirable] effect of this is that the array is iterated in reverse order. But the syntax is small and concise.
    My first thought about that is "is there a special reason why you're iterating over it in reverse order?"
    Closely followed by "Is he wanting to optimising for speed? What is it in this loop that has such a high demand?"
    Most often followed up by "Oh, the code doesn't need such performance enhancements. He's doing this instead to demonstrate that he knows about such techniques."

    So in summary, what is the code saying to the person who will be reading it?

    In terms of loops though, I agree with Felgall in all parts, except for the parenthesis hanging off the end.

    I prefer to use:
    Code javascript:
    (function () {
        ...
    }());

    So that the normal consistent structure of a function is maintained, where the braces are directly followed by the parenthesis for arguments.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  13. #13
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,197
    Mentioned
    456 Post(s)
    Tagged
    8 Thread(s)
    As an aside, I was watching Crockford yesterday lampoon the use of i++ instead of i += 1.

    Anyhow, I've been learning about the different ways to invoke functions, and am surprised at how many ways there are to call functions. I've been intrigued over the difference between

    Code javascript:
    (function () {
        ...
    }());

    and

    Code javascript:
    (function () {
        ...
    })();

    Is there a subtle difference in meaning? It seems weird that it can be either way around.
    Last edited by ralph.m; Apr 24, 2013 at 20:52. Reason: "invoke", not "call"

  14. #14
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by ralph.m View Post
    Is there a subtle difference in meaning? It seems weird that it can be either way around.
    In both cases, the function is changed from being a function declaration to a function expression, by wrapping parenthesis around the whole lot.
    Due to it now being a function expression, it can also be invoked at the same time, which gives us a self-invoking (or executing) function.

    With the first example the () parenthesis invokes the function, all of which are wrapped by the parenthesis that allow it to be a function expression.
    With the second example, the () invokes the whole lot that's wrapped by the outer parenthesis.

    The outcome for both are exactly the same, so whichever one you use tends to come down to a matter of personal style and taste. Or it can be due to a style guide that you follow.

    For me, I prefer the former, because it's more consistent with how other function expressions are used.

    Code javascript:
    var invokedFunction = function () {
        ...
    }();
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  15. #15
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,813
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    I think the use of i, j etc for loop variables goes back to ForTran where i was the first single character integer variable name - all the earlier letters of the alphabet were for floating point.

    Best practice is to use one var statement at the top of the function to declare all the variables at the spot where JavaScript itself will actually declare them. That way the code matches the way it will run and it is far easier to see which variables the function uses as they are all together in one place at the top of the function.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •