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 :)
-
Can you put the writers code in your question just for comparison?webdad3– webdad32011年04月02日 19:48:23 +00:00Commented Apr 2, 2011 at 19:48
-
2Young 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/…karim79– karim792011年04月02日 19:50:53 +00:00Commented 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.Mohammad Fadin– Mohammad Fadin2011年04月02日 19:59:47 +00:00Commented Apr 2, 2011 at 19:59
1 Answer 1
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 ++)
// ^^^^^^^^^^^^
3 Comments
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>;}