Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 24
  1. #1
    New Coder
    Join Date
    Sep 2010
    Location
    High Wycombe, UK
    Posts
    26
    Thanks
    4
    Thanked 0 Times in 0 Posts

    for loop parameter omission

    Hello.

    I wish to skip the 2nd parameter from a "for loop".
    Yes, i know it will run forever, but that is what I want for now.
    I'll add the BREAK later once I have got this mastered.
    would something like:
    for (Count = 1; ; Count++)
    be the correct syntax?
    or would recommend cheating as thus:
    for (Count = 1; Count > 0; Count++)

    Thanks,
    Morlaf
    Morlaf - Learning JavaScript!

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    3,762
    Thanks
    23
    Thanked 548 Times in 547 Posts
    Use a do loop instead
    Code:
    var something = 1;
    while (something == 1)
      {
      code block to be executed
      }
    Evolution - The non-random survival of random variants.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by Morlaf View Post
    I wish to skip the 2nd parameter from a "for loop".
    Why do you want to do that? I would suggest you would do better to learn Javascript rather then seek ways to contort it.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #4
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Quote Originally Posted by Morlaf View Post
    would something like:
    for (Count = 1; ; Count++)
    be the correct syntax?
    Why don't you just try it?

    Generally spoken, infinite loops (with a hidden break statement inside) are considered very bad practice with few exceptions. There is almost always a better way.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    all params on the for loop are indeed optional:

    Code:
    var i=0; 
    for(;;){
     if(i++>10)break;
    }
    alert(i);
    the first segment is not needed, it's sugar to make JS look like block-scoped C/JAVA code.
    the 2nd segment is evaluated for truthyness before the opening "{" is reached ala while(), but it's not needed.
    the 3rd segment is evaluated after the closing "}", but it to is optional, since you might not need to do anything each iteration.
    Last edited by rnd me; 05-23-2013 at 05:55 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    alert (i) results in 12. I can quite see why but the result is not what most people would expect. I cannot see any sensible reason for using such a construct.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by Philip M View Post
    alert (i) results in 12. I can quite see why but the result is not what most people would expect. I cannot see any sensible reason for using such a construct.
    I think RndMe's point was only to point out that none of the three segments in a for are required.

    As to why the result is 11: Easy.

    Remember, the POST-increment operator (i++) means that the value of the variable is incremented *AFTER* the expression you find it in is evaluated.

    So look at the last few iterations of RndMe's code:
    Code:
    ... after several iterations and i is bumped to 9 ...
    i is now 9, execute  if(i++>10)break;
        i is not > 10, so don't break.  But after making that decsion, bump i to 10
    i is now 10, execute  if(i++>10)break;
        i is not > 10, so don't break.  But after making that decsion, bump i to 11
    i is now 11, execute  if(i++>10)break;
        i *IS* > 10, so *DO* break.  But after making that decsion, bump i to 12
    alert(i) so alert the number 12
    RndMe was emulating the more normal for loop of
    Code:
    for ( var i = 0; i <= 10; i++ )
    { 
       ... do something ...
    }
    alert(i);
    But it's not a perfect emulation, because in the case of the for loop the test (i <= 10) and the increment are performed separately. In fact, there's no difference between
    Code:
    for ( var i = 0; i <= 10; i++ )
    and
    Code:
    for ( var i = 0; i <= 10; ++i )
    Not so when you combine the increment with the if test. It's one reason I avoid using post-increment *except* in the very very rare case where I really need it. Most people simply don't see the difference between pre and post increment (and decrement) and expect it to always function the way pre-increment does. But clearly (as in the above) that is not the case.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    Quote Originally Posted by Philip M View Post
    alert (i) results in 12. I can quite see why but the result is not what most people would expect. I cannot see any sensible reason for using such a construct.
    i never said such coding was intuitive or recommended, just that it does (along with a lot of other crap in JS) work.

    there are some reasons to do this. for can save a few bytes over while in bookmarklets. the loop can run faster without any boiler-plate work each iteration. it gives you a named break point in nested loops. hmm, there was one more i had before i clicked reply. maybe something about really really old browsers or js stamps? hmm, dunno, dang...

    in any case, i like placeholders in my for loops even if they don't do anything and slow down old browsers; it just looks better.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Possible other reason?

    Sometimes it's more intuitive to use xxx > yyy than it is to use xxx <= yyy??

    Of course you could have written
    Code:
    do {
       ...
    } while( ! ( i++ > 10 ) );
    One thing I do miss in JavaScript (and other languages) is until. Would be nice to be able to write
    Code:
    do {
       ...
    } until ( i++ > 10 );
    But of course until ( condition ) is the same as while ( ! condition ), so it's just syntactic sugar.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    And of course if you really wanted to use the post-increment value of i in the loop, your break does that:
    Code:
    var i=0, z=0, y=0;
    for ( ;; )
    {
        z += i;
        if ( i++ > 10 ) break;
        y += i;
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #11
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,462
    Thanks
    0
    Thanked 633 Times in 623 Posts
    Quote Originally Posted by Philip M View Post
    alert (i) results in 12. I can quite see why but the result is not what most people would expect.
    It is EXACTLY what I would expect.

    if ( i++ > 10 ) break;

    is identically in processing to:

    if ( i > 10 ) {i++; break};
    i++;


    The comparison will be true when i is 11 and then you add one more to it giving the expected result of 12.

    To get the result of 11 that apparently you expected you would need to use:

    if (++i > 10 ) break;

    which is equivalent in processing to:

    i++;
    if ( i > 10 ) break;


    Which side of the variable the ++ is on determines whether that addition is done first of last when combined with other processing in the same statement - one reason why using ++ produces a warning when you run code using it through jslint - since it leads to misunderstandings in how code works just like this example.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Slow, Felgall, slow. I beat you by over 90 minutes. <grin/>

    I 100% agree with you about post increment/decrement operators. As I said, I never use them except in the very very rare cases where I actually need the effect. As a minor aside, even with highly optimized compilers they need one more machine instruction than pre increment/decrement (unless being compared to a constant, in which case the compiler can change the constant silently). I suspect that the cost in JavaScript is somewhat higher (though of course not noticeable in normal operations).
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    i think we all know why it's 12, but i will admit that when i pounded it out and pasted it into firebug without thinking i was expecting a 10 or 11...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #14
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,462
    Thanks
    0
    Thanked 633 Times in 623 Posts
    Quote Originally Posted by Old Pedant View Post
    Slow, Felgall, slow. I beat you by over 90 minutes. <grin/>
    I was just adding the piece missing from your explanation - showing how the single statement in the acual code looks when you split out the increment into a separate statement. I thought it might help others reading the thread in future to understand the difference between pre and post increments better if they see that as well as read your explanation.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Yes, I saw that. It's an excellent point. I was just teasing.

    I really think that your explanation of the post increment mechanism was great:

    if ( i > 10 ) {i++; break};
    i++;

    It shows clearly that the increment has to happen no matter or not whether the if condition is true.

    FWIW, in an optimized compiler, if ( i++ > j ) must be executed something like this:
    Code:
    load r0, j   ; get value of j into one register
    load r1, i   ; and value of i into another
    inc r1       ; do the ++
    store r1, i   ; put the value back in i
    dec r1      ; back to the original value of i
    cmp r1, r0   ; do the comparison
    bgt someplace ; if i > j then jump
    With a preincrement if ( ++i > j ) the dec r1 instruction will be omitted.

    A really smart optimizing compiler, though, could do better with if ( i++ > 10 )
    Code:
    load r1, i   ; and value of i into another
    inc r1       ; do the ++
    store r1, i   ; put the value back in i
    cmp r1, #11   ; compare vs. 11 instead of 10 !!!
    bgt someplace ; if i > 10 same as if (i++) > 11, so then jump
    I would guess that the JavaScript compiler probably doesn't do that well in either case, since it probably emulates a stack based machine instead of a multi-register machine (much easier to compile for stack-based).
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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