View Full Version : Help understanding this function!

laylo

08-20-2011, 09:30 AM

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.

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.

Philip M

08-20-2011, 09:59 AM

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? :)

laylo

08-21-2011, 11:53 AM

Thank you my friend! Your comments really helped.

Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.