Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: Local variables in a for() loop?

  1. #1
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default Local variables in a for() loop?

    Hi all,

    What is the best way to declare a variable within a for() loop so that it is not accessible from outside of the loop?

    Thanks!
    Last edited by jlizarraga; 01-09-2009 at 12:12 AM. Reason: resolved

  2. #2
    Join Date
    Jun 2008
    Posts
    589
    Thanks
    13
    Thanked 54 Times in 54 Posts
    Blog Entries
    1

    Default

    It isn't accessible from outside of the loop... If you have a global variable name and you use the same name in a "for" loop, it won't work cuz it's illegal. I don't quite understand how your question would be executed (considering your asking if something possible, and it already is...). Any clarifications, or did you mean exactly that? Also, could you post code that you are using so that we can give a firm solution? In closing, you should always create a for loop variable the same way you do with others: for(var i = 0; i < 10; ++i); (etc.)

    Edit: var may make 'i' global- I don't know...


    -magicyte
    Last edited by magicyte; 01-07-2009 at 11:45 PM.

  3. #3
    Join Date
    Jan 2008
    Posts
    4,168
    Thanks
    28
    Thanked 628 Times in 624 Posts
    Blog Entries
    1

    Default

    Magic - you can access it from the outside:
    Code:
    <script type="text/javascript">
    for(i=0;i<=10;i++){
    var end = i;
    }
    alert(end);
    </script>
    The end variable is declared inside the for, and can be accessed outside the end.
    [edit]
    I've just realized what magicyte meant, you were talking about the i=0, I'm talking about a variable in the { and }. Can you please specify which variables? Mine or magics.
    Last edited by Nile; 01-07-2009 at 11:31 PM.
    Jeremy | jfein.net

  4. #4
    Join Date
    Jun 2008
    Posts
    589
    Thanks
    13
    Thanked 54 Times in 54 Posts
    Blog Entries
    1

    Default

    Oh- in that case, you COULD make it private SOMEHOW. I may have forgotten, though.

    -magicyte
    Last edited by magicyte; 01-08-2009 at 10:04 PM.

  5. #5
    Join Date
    Jan 2008
    Posts
    4,168
    Thanks
    28
    Thanked 628 Times in 624 Posts
    Blog Entries
    1

    Default

    No - that will still be global.
    Jeremy | jfein.net

  6. #6
    Join Date
    Jun 2008
    Posts
    589
    Thanks
    13
    Thanked 54 Times in 54 Posts
    Blog Entries
    1

    Default

    Darn...

    Anyway, why would you not want your variable being declared inside of the for() loop accessed outside? You wouldn't NEED to access it unless you had the same variable name in a global scenario... That should flag an error, though.

    -magicyte
    Last edited by magicyte; 01-08-2009 at 10:05 PM.

  7. #7
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    To make a variable local, regardless of whether or not it is in a loop, it must be in its own function. If the loop is already in a function, simply formally declaring the variables used within the loop will make them local to that function.

    If you want them local to the loop, and only to the loop, put the loop itself in a separate function, ex:

    Code:
    var preload_looper = function(ar){
     for(var par = [], i = 0; i < ar.length; ++i){
      par[i] = [ar[i], new Image()];
      par[i][1].src = par[i][0];
     }
    };
    The variables par, and i will be local to the function, and therefore the loop. And since nothing is done to the passed array (ar), it will not be changed by the function or the loop.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  8. #8
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,627
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    Based on what John said above here is another example that uses an anonymous function through which it maintains a private variable.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    		<title>Untitled Document</title>
    		<style type="text/css">
    		</style>
    		<script type="text/javascript">			
    			for(var i = 0; i < 10; i++){
    				(function(){
    					var k = i;
    					alert(k);
    				})(); //Self executing anonymous function
    			}
    			alert(typeof k); //You are trying to access the variable k here. This will give you 'undefined' as its value.
    		</script>
    	</head>
    	<body>
    	</body>
    </html>
    JavaScript doesn't allow block level variables whose scope is the block in which it declared.

    Hope this helps.

  9. #9
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Oh- in that case, you COULD make it private SOMEHOW. I may have forgotten, but this is the way I think that it goes:
    Code:
    for(var i = 0; i < 10; ++i) {
      yourVariable = "whatever";
    }
    No, that will make it global, not even limited to the function scope as it would be with a var keyword (technically speaking, you're declaring a property of the global object rather than a variable).

    Javascript doesn't, as magicyte has just (like many C programmers before him) found out, have block scope. The only way to create a new scope (at least until JS1.7 with its let blocks has better support) is with a separate function, as John and codeexploiter have demonstrated; however, there is one flaw in codeexploiter's model: on each iteration, the function will be created anew. That's quite nastily inefficient. Better would be to create a separate function elsewhere, passing in assorted variables where necessary. In terms of codeexploiter's loop:
    Code:
    var looper = (function() {
      function helper(i) {
        var k = i;
        alert(k);
      }
    
      function looper() {
        for (var i = 0; i < 10; ++i)
          helper(i);
      }
    
      return looper;
    })();
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  10. #10
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    That's not merely local (private), it's downright exclusive. But it does fit the bill.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

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
  •