How can I use goto in Javascript?

Peter Olson picture Peter Olson · Mar 17, 2012 · Viewed 263.6k times · Source

I have some code that I absolutely must implement using goto. For example, I want to write a program like this:

start:
alert("RINSE");
alert("LATHER");
repeat: goto start

Is there a way to do that in Javascript?

Answer

Peter Olson picture Peter Olson · Mar 17, 2012

Absolutely! There is a project called Summer of Goto that allows you use JavaScript at its fullest potential and will revolutionize the way you can write your code.

This JavaScript preprocessing tool allows you to create a label and then goto it using this syntax:

[lbl] <label-name>
goto <label-name>

For example, the example in the question can be written as follows:

[lbl] start:
alert("LATHER");
alert("RINSE");
[lbl] repeat: goto start;

Note that you are not just limited to simple trivial programs like an endless LATHER RINSE repeat cycle—the possibilities afforded by goto are endless and you can even make a Hello, world! message to the JavaScript console 538 times, like this:

var i = 0;
[lbl] start:
console.log("Hello, world!");
i++;
if(i < 538) goto start;

You can read more about how goto is implemented, but basically, it does some JavaScript preprocessing that takes advantage of the fact that you can simulate a goto with a labelled while loop. So, when you write the "Hello, world!" program above, it gets translated to something like this:

var i = 0;
start: while(true) {
  console.log("Hello, world!");
  i++;
  if(i < 538) continue start;
  break;
}

There are some limitations to this preprocessing process, because while loops cannot stretch across multiple functions or blocks. That's not a big deal, though—I'm sure the benefits of being able to take advantage of goto in JavaScript will absolutely overwhelm you.

All above link that lead to goto.js library is ALL DEAD, here is links needed:

goto.js (uncompressed) --- parseScripts.js (uncompressed)

From Goto.js:

P.S. For anyone who is wondering (so far a total of zero people), Summer of Goto is a term that was popularized by Paul Irish, while discussing this script and PHP’s decision to add goto into their language.

And for those who do not immediately recognize that this entire thing is a joke, please forgive me. <—(insurance).