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 🙂
A
forloop‘s syntax must beWhile any of
<initializer>,<condition>and<increment>can be omitted, none of the semicolons;can be removed. That means, yourforloop must be written with an extra semicolon:Or just move the
var num = 1;into thefor, which is normally what people would do: