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.
Results 1 to 3 of 3

Thread: Local Variables

  1. #1
    JPM
    JPM is offline
    Regular Coder
    Join Date
    Mar 2004
    Location
    Norway
    Posts
    204
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Local Variables

    It seems to me that if you have to functions, both with a local variable 'n', and the first function calls the second function and the second function increases the value of n, say in a while loop, the value of n will also have been increased in the first function when it continues.

    I came across this problem while translating some simple code from Python to js.

    Here is the js code. Change 'i' to 'x' in function printMultiples and it works, otherwise the value of i in printTables has been increased above the 'high' parameter when printMultiples is done and printTables continues


    Code:
    <html>
    <body>
    <script>
    
    function printMultiples(n,high)
    {
      i = 1
      while(i<=high)
      {
        document.write(n*i +"&nbsp;&nbsp;&nbsp;&nbsp; ")
        alert(n*i)
        i++ // also increases i in printTables
      }
      document.write("<br />")
    }
    
    function printTables(high)
    {
      i = 1
      while (i < high)
      {   
        printMultiples(i,high)
        i++
        alert(i + " printTables")
      }
    }
    
    printTables(5)
    
    </script>
    </body>
    </html>
    I would have understood this if there was a global variable i...?
    Last edited by JPM; 08-12-2004 at 12:32 PM.
    <JPM />

  • #2
    Banned
    Join Date
    Sep 2003
    Posts
    3,620
    Thanks
    0
    Thanked 0 Times in 0 Posts
    There's not one local variable in your entire script....

    Without using the keyword var for your variables within your function calls....
    Your variables are global....


    .....Willy

  • #3
    JPM
    JPM is offline
    Regular Coder
    Join Date
    Mar 2004
    Location
    Norway
    Posts
    204
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks! now that I think about it I remember reading that before
    Last edited by JPM; 08-12-2004 at 01:31 PM.
    <JPM />


  •  

    Posting Permissions

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