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
  1. #1
    New Coder
    Join Date
    Jul 2011
    Posts
    19
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Help understanding this function!

    I put this function in firebug and it returns the value 24. I just need help of someone explaning me as simple but descriptive as possible how the code works.

    Code:
    function factorial(n) {
    var product= 1;
    while(n > 1) {product *= n;
    n--;
    }
    return product;
    }
    factorial(4)
    i was just reading a book and these were just one of the examples of functions which I was trying to understand better.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,907
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    function factorial(n) { // the value of n (here 4) is passed to the function
    var product = 1; // initialise the variable product to 1
    while (n > 1) { // loop repeatedly while the value of n is a number greater than 1 (the initial value is 4)
    alert (product + " " + n); // to observe the detail of the operation
    product *= n; // multiply the current value of product by the current value of n (a shorthand for product = product * n)
    // first pass 1 * 4 = 4
    // second pass 4 * 3 = 12
    // third pass 12 * 2 = 24
    // fourth pass - n is now 1 so while loop terminates (no need to multiply by 1)
    alert (product); // to observe intermediate result
    n--; // subtract 1 from the value of n (same as n = n-1)
    } // do the while loop again as long as n is greater than 1

    alert (product); // final result 24 = 4*3*2*1 (or 4! in maths notation)
    return product; // return the value of product to the calling function
    }

    factorial(4); // call the function passing the value 4 to it


    OK?
    Last edited by Philip M; 08-20-2011 at 09:59 AM.

    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.

  • Users who have thanked Philip M for this post:

    laylo (08-21-2011)

  • #3
    New Coder
    Join Date
    Jul 2011
    Posts
    19
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Thank you my friend! Your comments really helped.


  •  

    Posting Permissions

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