0

I have question concerning the difference of using in JavaScript code comma OR semicolon.

Do they have differences and influence how the code works?

In the code below I changed the semicolon after definition of var fib that have value 0 by comma an code didn't run.

Can somebody explain this?

The full code of Fibonacci in which it has occurred is here:

<script>
    document.write("<h2>Числа Фибоначчи </h2>");
    for (i = 0, j = 1, k = 0, fib = 0; i < 50; i++, fib = j + k, j = k, k = fib) {
        document.write("Fibonacci (" + i + ") = " + fib);
        document.write("<br>");
    }
</script>
Nope
  • 22,147
  • 7
  • 47
  • 72

3 Answers3

0

for encloses 3 expressions :

  • the initialization (run before the loop),
  • the end of loop test (run before each iteration),
  • and the after iteration statement.

Statements in javascript are separated by ;. If you change the ; to a ,, you don't end the init statement.

drunken bot
  • 486
  • 3
  • 8
0

The part that probably confuses you is the fact that a 'normal' for-loop takes three statements like the following:

for (var i=0; i<5; i++)
  {
  x=x + "The number is " + i + "<br>";
  }

but that your example substitutes these expressions with comma seperated arguments.

var i=0 -> i = 0, j = 1, k = 0, fib = 0

i++ -> i++, fib = j + k, j = k, k = fib

BTW, this is terrible code that reads very hard and is even harder to maintain. Don't use it.

Jan Groth
  • 14,039
  • 5
  • 40
  • 55
0

The previous answers are indeed correct, but I think this is not about the for - it is about the comma, which is in fact an operator:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. - MDC

If you want to learn more about it: Angus C. elaborately explains what it does in his blog.

svckr
  • 791
  • 6
  • 11