SitePoint Sponsor

User Tag List

Results 1 to 24 of 24
  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
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,803
    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="^$">

  7. #7
    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

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    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

  9. #9
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,167
    Mentioned
    453 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.

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    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

  11. #11
    Just Blow It bronze trophy
    DaveMaxwell's Avatar
    Join Date
    Nov 1999
    Location
    Mechanicsburg, PA
    Posts
    7,263
    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

  12. #12
    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?

  13. #13
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,276
    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.

  14. #14
    Just Blow It bronze trophy
    DaveMaxwell's Avatar
    Join Date
    Nov 1999
    Location
    Mechanicsburg, PA
    Posts
    7,263
    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

  15. #15
    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
    Nope, not at all. There's nothing wrong with them at all.
    Cool.

    Quote Originally Posted by DaveMaxwell View Post
    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.
    Ah okay, then I fear we got our wires crossed a little.
    What I actually meant was that I would personally leave the code just as the OP had it:

    Code JavaScript:
    for(var i = 0; i < array1Length; i++){ console.log("loop 1"); }
    for(var i = 0; i < array2Length; i++){ console.log("loop 2"); }
    for(var i = 0; i < array3Length; i++){ console.log("loop 3"); }
    (Although in hindsight, I would take on board felgall's and Paul's suggestions)

    However, jimmybrion had previously suggested changing the variable names to 'i', 'j' and 'k'.
    This is by no means wrong, but I was making the point that I would only do this if the loops were nested:

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

  16. #16
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Pullo View Post
    However, jimmybrion had previously suggested changing the variable names to 'i', 'j' and 'k'.
    And further on from there, it would be useful to consider changing them from i,j,k if the named counterparts result in making the intention of the code easier to understand.

    Because it is a standard practice to use i as a loop index, if the intention of the loop is for something else then that a good time to to use something else other than i, so that people don't misunderstand what the index is being used for.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  17. #17
    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 paul_wilkins View Post
    And further on from there, it would be useful to consider changing them from i,j,k if the named counterparts result in making the intention of the code easier to understand.

    Because it is a standard practice to use i as a loop index, if the intention of the loop is for something else then that a good time to to use something else other than i, so that people don't misunderstand what the index is being used for.
    Just to clarify, do you mean like Thom's example?

    Code JavaScript:
    for(var people = 0; people < peopleArrayLength; people++){ ... }
    for(var address = 0; address < addressArrayLength; address++){ ... }
    for(var email = 0; email < emailArrayLength; email++){ ... }
    Quote Originally Posted by Stomme poes View Post
    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.
    I've just been reading up on this. It seems they're called Array Comprehensions and are available as of JavaScript 1.7

    This effectively means that instead of this:

    Code JavaScript:
    var nums = [1,2,3,4,5,6,7,8,9], greaterThanFive = [];
    for(var i=0; i < nums.length; i++){
      if (nums[i] > 5){
        greaterThanFive.push(nums[i]);
      }
    }
    I can write this:

    Code JavaScript:
    var nums = [1,2,3,4,5,6,7,8,9];
    var greaterThanFive = [i for (i of nums) if (i > 5)]
    And instead of this:

    Code JavaScript:
    var nums = [[1,2,3],[4,5,6],[7,8,9]], greaterThanFive = []
    for(var i=0; i < nums.length; i++){
      for(var j=0; j < nums[i].length; j++){
        if (nums[i][j] > 5){
          greaterThanFive.push(nums[i][j]);
        }
      }
    }
    I can write:

    Code JavaScript:
    var nums = [[1,2,3],[4,5,6],[7,8,9]]
    var greaterThanFive = [j for (i of nums) for (j of i) if (j > 5)]
    I didn't know you could do that. Thanks, poes.

    N.B. They're horrid examples, I know, and could certainly be written better. I just wanted to play around with the comprehension thingies.

  18. #18
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Pullo View Post
    Just to clarify, do you mean like Thom's example?
    Yes, something like that. Good examples tend to be difficult to come up with because as soon as they're created, other forms of structures are seen to be better.

    But for the sake of example, I'm meaning something like this:

    Code javascript:
    for (width = 0, width = maxWidth; width += 1) {
        for (height = 0, height = maxHeight; height += 1) {
            doSurfaceThingAt(width, height);
            for (depth = 0, depth = maxDepth; depth += 1) {
                doSomethingAt(width, height, depth);
            }
        }
    }

    So that you end up with

    Code:
    doSomethingAt(width, height, depth);
    Instead of
    Code:
    doSomethingAt(I, j, k);
    Or even
    Code:
    doSomethingAt(x, y, z);
    Because is y gong vertical, or is it an x/y plane on the ground? Such questions are easily answered with more expressive names.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  19. #19
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,803
    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="^$">

  20. #20
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,167
    Mentioned
    453 Post(s)
    Tagged
    8 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    In both cases, the function is changed from being a function declaration to a function expression ...
    Thanks for the explanation, Paul. It's also nice to know the names 'function expression', as now I can look it up. (Was having trouble working out what that syntax was called.)

    Quote Originally Posted by Stomme poes View Post
    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.
    You can watch it here: http://www.youtube.com/watch?v=taaEzHI9xyY&t=50m50s . I guess he is talking from a high level here, but still, he makes a fair point (that x += 1 isn't necessarily exactly the same as x++). I also like his little joke, that "the last popular language with point arithmetic was C++, a language so bad it was named after this operator".

    I like the plus because it looks funky:
    +function(){foobarbaz;}();
    Egad, another one? I hadn't come across that one.

  21. #21
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,276
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    Ralph: oh, I have The Good Parts, there's a long-enough rant about i++ in there as well. I still wasn't swayed. He likes i +=1 because it's more explicit, same reason Python doesn't do i++ either. Explicit over implicit, as the Zen says.

    Quote Originally Posted by felgall
    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.
    I thought it was from "incrementor", which I think I have in my ANSI-C (K&R) book... first they start out using the whole word, then the next example shortens it to "i". The other word they used, with while loops, was "counter" but I don't remember if they ever shortened that to "c" :p


    Pullo:
    even more goodies...
    Javascript 1.8 has lamda-style and generators.
    lamdas in Python are just basically inline functions. They do what functions do, but are statements. So, an anonymous inline function who is a statement rather than an object. In Python they're basically used like one-offs. In Javascript, who already knows anonymous functions, I think it would just be a slightly cleaner big of code here and there maybe... not sure why they added it, actually.

    Generators are pretty cool: basically you may have a function who is supposed to loop through things and return values to another function who's calling for them. Normally, a function would run through its loop until it's finished, and exit. People wanting to avoid this behaviour would try closures (who would still run all at once) or callbacks (run something after a loop value was returned maybe). Here, a generator has the "yield" keyword: it basically pauses the function, instead of exiting like return, and lets the original caller call it again, where it picks back up right where it left off. The only part stored in memory is the part of the loop you're at, instead of the whole list, because the function is only creating one "loop" at a time.

  22. #22
    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)
    Hi poes,

    Quote Originally Posted by Stomme poes View Post
    Javascript 1.8 has lamda-style and generators.
    lamdas in Python are just basically inline functions. They do what functions do, but are statements. So, an anonymous inline function who is a statement rather than an object. In Python they're basically used like one-offs. In Javascript, who already knows anonymous functions, I think it would just be a slightly cleaner big of code here and there maybe... not sure why they added it, actually.
    Procs and Lambdas I know from Ruby. They're pretty useful in their own right as they allow you to save reusable code as an object and, well, reuse it.
    However, unless I've missed something, for a language such as JavaScript that already has anonymous functions, they don't add much in the way of functionality, just a little syntactic sugar.

    Quote Originally Posted by Stomme poes View Post
    Generators are pretty cool: basically you may have a function who is supposed to loop through things and return values to another function who's calling for them. Normally, a function would run through its loop until it's finished, and exit. People wanting to avoid this behaviour would try closures (who would still run all at once) or callbacks (run something after a loop value was returned maybe). Here, a generator has the "yield" keyword: it basically pauses the function, instead of exiting like return, and lets the original caller call it again, where it picks back up right where it left off. The only part stored in memory is the part of the loop you're at, instead of the whole list, because the function is only creating one "loop" at a time.
    I had to look up what generators are in Python and they seem quite close to Ruby's Enumerator class.
    When you get into doing something a little more intense than changing CSS styles on the fly, I can imagine they'd be very useful.

    Just having a little play around with this idea, I found this code on MDN, which will calculate the first 'n' values in the Fibonacci sequence:

    Code JavaScript:
    function fibonacci(n){
      var fn1 = 1;
      var fn2 = 1;
      for(var i=0; i<n; i++){
        var current = fn2;
        fn2 = fn1;
        fn1 = fn1 + current;
        yield current;
      }
    }

    This is cool as, as you point out, you can then step through the values and have them calculated one at a time, as opposed to create them all in memory in one go.

    Code JavaScript:
    var sequence = fibonacci(10000000);
    console.log(sequence.next()); // 1
    console.log(sequence.next()); // 1
    console.log(sequence.next()); // 2
    console.log(sequence.next()); // 3
    console.log(sequence.next()); // 5

    I guess this is getting right off-topic now, so I'll stop.
    Thanks for pointing all of that out. It's nice to use JavaScript for something other than webpage manipulation

  23. #23
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,803
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Stomme poes View Post
    I thought it was from "incrementor", which I think I have in my ANSI-C (K&R) book
    To the best of my knowledge it was used in ForTran in 1954 whereas C wasn't invented until the 1970s.

    The use of single character variable names was very common in early ForTran as the computers only had a few hundred bytes available. The variables 'a' through 'h' were for floating point numbers and so 'i' was the obvious choice for the first integer that the program used. It didn't really matter what the variable was going to be used for at that point so possibly its becoming restricted to use with loops occurred with C - although the computers I was working with in the late 70s still mostly only had a couple of hundred bytes of memory available so using longer variable names could result in the program being unable to compile.
    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="^$">

  24. #24
    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 Stomme poes View Post
    In Javascript, who already knows anonymous functions, I think it would just be a slightly cleaner big of code here and there maybe... not sure why they added it, actually.
    Still playing around with lambdas and fund out you can do this:

    Code JavaScript:
    Array.prototype.iterate = function(lambda){
      return [lambda(i) for (i of this)] 
    }
     
    var arr = [1,2,3,4,5];
    var lambda = function(x) x * x;
    console.log(arr.iterate(lambda));
     
    // [1, 4, 9, 16, 25]

    Bit pointless really, but good fun.

    I'll shut up now ...


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
  •