0

i get reference from here "How can I use goto in Javascript?"

i understand the code as below

[lbl] first:
alert("Test")
goto first;

however. why the code below does not work for me

goto end;
alert("skipped line");
[lbl] end:

when I run the above command I will get an error like thisenter image description here

Community
  • 1
  • 1
Error Person
  • 33
  • 1
  • 4
  • Because `end` is not a label. Labels in JavaScript have the form `label: statement` (granted the preprocessing tool might be able to handle that case, but apparently it does not). – Felix Kling Jun 24 '15 at 02:28
  • `[lbl] end: ;` might work. `end:` is the label and `;` is the empty statement. – Felix Kling Jun 24 '15 at 02:35
  • sorry i misstype. i update my questions – Error Person Jun 24 '15 at 02:39
  • 3
    Well the obvious comment here is to never use `goto` in the first place. It's considered an evil construct by many. Instead, use conditionals, loops, functions, methods and return statements to construct your flow. – jfriend00 Jun 24 '15 at 02:44
  • i still not understand what evil? :v – Error Person Jun 24 '15 at 02:53
  • @ErrorPerson - it's harder to maintain than other alternatives, requiring more effort to understand the same program flow. Sure, when writing in x86 asm, you've no choice but to use the either JMP or the LOOP instructions. (not sure how common the loop instruction is, all hardware have a JMP) But it's an uncivilized way to write high level code. One that increases people's propensity to generate errors. – enhzflep Jun 24 '15 at 02:58

1 Answers1

2

Labels are for loops and blocks.

Loop usage:

var allPass = true
top:
for(var i=0; i < items.length; ++i)
    for(var j=0; j < tests.length; ++j)
        if(!tests[j].pass(items[i])){
            allPass = false
            break top
        }

You can also use continue label.

Block usage:

foo: {
    console.log("face")
    break foo
    console.log("this will not be executed")
}
console.log("swap")

Non-strict, non-generator, function usage:

L: function F(){}
Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124