Thursday, November 27, 2014

Today I learned: JavaScript's continue is only allowed in loops


Reading through the basics of JavaScript, I wondered whether you could simulate a while statement with a switch statement. You might ask yourself: Wait, what?

Let me explain: I thought some crazy thoughts. If you could combine labels, a dynamic case statement, and the continue statement, you could fake the while loop. Let's look at an example:

Let's compute some Fibonacci numbers, the classical way.

var a = [0, 1],
    num = 10,
    i = a.length,
    result;

while (i < num) {
   a.push(a[i - 1] + a[i - 2]);
   i += 1;
}

And so I thought to myself, maybe you could do something like that instead of the while loop.

loopMe:
switch (i) {
  case i < num:
    a.push(a[i - 1] + a[i - 2]);
    i += 1;
    continue loopMe;
  default:
    break;
}

I was an idiot, and JavaScript told me so:

 Uncaught SyntaxError: Undefined label 'loopMe'

When I removed the label after continue, I still was an idiot, and JavaScript told me so:

Uncaught SyntaxError: Illegal continue statement.

So there was no way to get this to work. continue statements are only allowed in loops, as I remembered.
The only funny thing was, that JavaScript bitched about unfound labels at first. And then about the misplaced continue statement.

Glad, I used two hours of my life on that one. But at least, I have learned something.
And that is what it's all about, isn't it?

1 comment:

  1. ha, ha... I ran into the exact same situation (also wasted some time on this). Add the classless concept of JS and, compared to a language like Python, JS looks like very poorly designed language. But we have to deal with it, until we gate something new (and hopefully better) :-)

    ReplyDelete