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?

6 comments:

  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
  2. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Java training in Chennai

    Java training in Bangalore

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. Thank you and good luck…

    Upgrade your career Learn Data Warehousing Training in Bangalore from industry experts get Complete hands-on Training, Interview preparation, and Job Assistance at Softgen Infotech.

    ReplyDelete
  5. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Salesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Certification Online Training Courses

    ReplyDelete