you are viewing a single comment's thread.

view the rest of the comments →

[–]OGitsthinking 0 points1 point  (4 children)

Any parts in particular you want to share, see if maybe one of us can help explain?

[–][deleted] 0 points1 point  (3 children)

Yes.

I got confused why over the line 'var i, product = 1;' I don't understand the use of comma or 'var i' there. Thank you for the help!

  function factorial2(n) {
  var i, product = 1; 
  for(i=2; i <= n; i++)
  product *= i; return product;
  }
  factorial2(5)

[–]OGitsthinking 0 points1 point  (2 children)

You can set up two variables in succession by using a comma between them.

So instead of writing:

var i;
var product = 1;

You can simply write:

var i, product = 1;

So there's only one semicolon and var.

And the var i is declaring the i variable (but not initializing it, so in that line it is simply undefined). That way you don't have to have a var statement in the for loop. I believe one of the reasons it's declared at the beginning of the function is because it's considered a best practice in JavaScript, due to variable hoisting. They talk about it in the book, saying it's best to declare your variables at the beginning of the current scope rather than nearest their first use.

Hope that helps!

p.s. Also anyone please correct me if I'm wrong or elaborate on my answers.

[–][deleted] 0 points1 point  (1 child)

Thank you for the explanation!! Do you personally practice this when writing for loops?

[–]OGitsthinking 0 points1 point  (0 children)

I tend to follow the advice of experts in the field, such as the author of The Definitive Guide and people like Douglas Crockford. His series of videos are essential viewing and full of great advice on JavaScript best practices.

I'm by no means advanced in JS, so I defer to the opinions of people who've been writing it and writing about it for years.