0

Today is my first day in JavaScript. The book (JavaScript Definitive Guide) has an excersice printing all the factorials.

This is what I did:

<html>
<b><head> Factorial - JavaScript - Ex1</head></b>
<body>
 <h2> Factorials List </h2>
<script>
 var fact = 1; 
 var num = 1;
 for(num <= 10; num++)
 {
 fact=fact*num;
 document.write(num + "! = " + fact + "<br>");
 }
</script>
</body>
</html>

There is a problem which I don't exactly know. I checked the book and the way that writer solved it was by initializing the variable num inside the loop FOR. I did that and it worked. But what is the difference between that and mine?

Enlighten me Experts :)

asked Apr 2, 2011 at 19:45
3
  • Can you put the writers code in your question just for comparison? Commented Apr 2, 2011 at 19:48
  • 2
    Young Padawan, you must read Douglas Crockford's JavaScript: The Good Parts - and each page needs about twenty read-agains. amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/… Commented Apr 2, 2011 at 19:50
  • Thanks @Jeff. It was a mistake I made actually. @karim79 yes this book is good too. But many people suggested me to start with JS By David. Commented Apr 2, 2011 at 19:59

1 Answer 1

9

A for loop's syntax must be

for (<initializer>; <condition>; <increment>) {
 <body>
}

While any of <initializer>, <condition> and <increment> can be omitted, none of the semicolons ; can be removed. That means, your for loop must be written with an extra semicolon:

var num = 1;
for(; num <= 10; num++)
// ^

Or just move the var num = 1; into the for, which is normally what people would do:

for (var num = 1; num <= 10; num ++) 
// ^^^^^^^^^^^^
answered Apr 2, 2011 at 19:49
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! I don't use FOR loop much not even in Java. This is really useful information. Okay but how about if I wanted to use While loop?
@Mohammad: var num=1;while(num<=10){<body>;num++;}. Actually the for loop is equivalent (if there's no break/continue) to a while loop in the form <initializer>;while(<condition>){<body>;<increment>;}
Thank you again. I really missed using {for loop}. I'm going to read about it and do some exercise for it in java first. much appreciated I also never started reading JS book the code was shown in the first chapter as an example on how client side looks like. But I started solving it :D

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.