Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use goto in Javascript?

People also ask

How do you use goto?

one: for (i = 0; i < number; ++i) { test += i; goto two; } two: if (test > 5) { goto three; } ... .. ... Also, the goto statement allows you to do bad stuff such as jump out of the scope. That being said, goto can be useful sometimes. For example: to break from nested loops.

What can I use instead of goto?

Alternatives to the “goto” are “break” and “continue”.

Can we use goto in function?

The goto statement can be used to jump from anywhere to anywhere within a function.

What is goto method?

GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control.


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).


No. They did not include that in ECMAScript:

ECMAScript has no goto statement.


In classic JavaScript you need to use do-while loops to achieve this type of code. I presume you are maybe generating code for some other thing.

The way to do it, like for backending bytecode to JavaScript is to wrap every label target in a "labelled" do-while.

LABEL1: do {
  x = x + 2;
  ...
  // JUMP TO THE END OF THE DO-WHILE - A FORWARDS GOTO
  if (x < 100) break LABEL1;
  // JUMP TO THE START OF THE DO WHILE - A BACKWARDS GOTO...
  if (x < 100) continue LABEL1;
} while(0);

Every labelled do-while loop you use like this actually creates the two label points for the one label. One at the the top and one at the end of the loop. Jumping back uses continue and jumping forwards uses break.

// NORMAL CODE
MYLOOP:
  DoStuff();
  x = x + 1;
  if (x > 100) goto DONE_LOOP;
  GOTO MYLOOP;


// JAVASCRIPT STYLE
MYLOOP: do {
  DoStuff();
  x = x + 1;
  if (x > 100) break MYLOOP;
  continue MYLOOP;// Not necessary since you can just put do {} while (1) but it     illustrates
} while (0)

Unfortunately there is no other way to do it.

Normal Example Code:

while (x < 10 && Ok) {
  z = 0;
  while (z < 10) {
    if (!DoStuff()) {
      Ok = FALSE;
      break;
    }
    z++;
  }
  x++;
} 

So say the code gets encoded to bytecodes so now you must put the bytecodes into JavaScript to simulate your backend for some purpose.

JavaScript style:

LOOP1: do {
  if (x >= 10) break LOOP1;
  if (!Ok) break LOOP1;
  z = 0;
  LOOP2: do {
    if (z >= 10) break LOOP2;
    if (!DoStuff()) {
      Ok = FALSE;
      break LOOP2;
    }
    z++;
  } while (1);// Note While (1) I can just skip saying continue LOOP2!
  x++;
  continue LOOP1;// Again can skip this line and just say do {} while (1)
} while(0)

So using this technique does the job fine for simple purposes. Other than that not much else you can do.

For normal Javacript you should not need to use goto ever, so you should probably avoid this technique here unless you are specificaly translating other style code to run on JavaScript. I assume that is how they get the Linux kernel to boot in JavaScript for example.

NOTE! This is all naive explanation. For proper Js backend of bytecodes also consider examining the loops before outputting the code. Many simple while loops can be detected as such and then you can rather use loops instead of goto.


Actually, I see that ECMAScript (JavaScript) DOES INDEED have a goto statement. However, the JavaScript goto has two flavors!

The two JavaScript flavors of goto are called labeled continue and labeled break. There is no keyword "goto" in JavaScript. The goto is accomplished in JavaScript using the break and continue keywords.

And this is more or less explicitly stated on the w3schools website here http://www.w3schools.com/js/js_switch.asp.

I find the documentation of the labeled continue and labeled break somewhat awkwardly expressed.

The difference between the labeled continue and labeled break is where they may be used. The labeled continue can only be used inside a while loop. See w3schools for some more information.

===========

Another approach that will work is to have a giant while statement with a giant switch statement inside:

while (true)
{
    switch (goto_variable)
    {
        case 1:
            // some code
            goto_variable = 2
            break;
        case 2:
            goto_variable = 5   // case in etc. below
            break;
        case 3:
            goto_variable = 1
            break;

         etc. ...
    }

}

const
    start = 0,
    more = 1,
    pass = 2,
    loop = 3,
    skip = 4,
    done = 5;

var label = start;


while (true){
    var goTo = null;
    switch (label){
        case start:
            console.log('start');
        case more:
            console.log('more');
        case pass:
            console.log('pass');
        case loop:
            console.log('loop');
            goTo = pass; break;
        case skip:
            console.log('skip');
        case done:
            console.log('done');

    }
    if (goTo == null) break;
    label = goTo;
}

This is an old question, but since JavaScript is a moving target - it is possible in ES6 on implementation that support proper tail calls. On implementations with support for proper tail calls, you can have an unbounded number of active tail calls (i.e. tail calls doesn't "grow the stack").

A goto can be thought of as a tail call with no parameters.

The example:

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

can be written as

 function start() { alert("RINSE");
                    alert("LATHER");
                    return start() }

Here the call to start is in tail position, so there will be no stack overflows.

Here is a more complex example:

 label1:   A
           B
           if C goto label3
           D
 label3:   E
           goto label1

First, we split the source up into blocks. Each label indicates the start of a new block.

 Block1
     label1:   A
               B
               if C goto label3
               D

  Block2    
     label3:   E
               goto label1

We need to bind the blocks together using gotos. In the example the block E follows D, so we add a goto label3 after D.

 Block1
     label1:   A
               B
               if C goto label2
               D
               goto label2

  Block2    
     label2:   E
               goto label1

Now each block becomes a function and each goto becomes a tail call.

 function label1() {
               A
               B
               if C then return( label2() )
               D
               return( label2() )
 }

 function label2() {
               E
               return( label1() )
 }

To start the program, use label1().

The rewrite is purely mechanical and can thus be done with a macro system such as sweet.js if need be.