SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: total=0

  1. #1
    SitePoint Zealot
    Join Date
    Mar 2011
    Posts
    146
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question total=0

    Hi,
    Im getting and error in firefox saying that total is not defined, However
    i think it is in blue. i understand the return statement concept just not how it works in conjuction with arrays.

    any help?

    function sum(numbers)
    {
    if (numbers.length ==0) return 0;
    for ( var i=0, total=0;i <numbers.length; i++)
    total+= numbers[i];

    return total;
    }

    document.getElementById("txtTotal").value = total;

  2. #2
    SitePoint Mentor bronze trophy
    chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,041
    Mentioned
    9 Post(s)
    Tagged
    1 Thread(s)
    It is correcting in saying that, when you use a var inside a function it becomes part of the local scope which is the function itself. If you declare the var outside the function it becomes part of the global scope so everything can use it.

    Basically you just need to update it so it looks like

    Code JavaScript:
    var total = 0;
     
    function sum(numbers) {
        if (!numbers.length) return 0;
     
        for (var i = 0; i < numbers.length; i++) {
            total += numbers[i];
        }
     
        return total;
    }
     
    document.getElementById("txtTotal").value = total;
    Blog/Portfolio | Evolution Xtreme | DFG Design | DFG Hosting | CSS-Tricks | Stack Overflow | Paul Irish
    Having lame problems with your code? Let us help by using a jsFiddle

Tags for this Thread

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
  •