No Goto in JavaScript:

I know that there is not goto statement in js.
But what do i need to do to achieve this in js.

for( let x = 0; x < 10; x++){
  for( let y = 0; y < 8; y++)
     if(y == 6){
       goto here;   // there is not goto statement
   }
}
here:
let my = 'get out of inner loop';

What i want to do here is get out of outer loop based on a condition inside innerloop;

If what you wanna do is get out of the for loop, you should check Break

I want to get out of outer loop too break just get me out of inner loop i.e that loop in which it is used.

Ah, ok. I don’t know if there is a good way to do that, I would try wrapping the for loop inside a function and use return to get out of it. Another idea would be:

let aux = false;
for (let x = 0; x < 10; x++) {
	for (let y = 0; y < 8; y++) {
		if (y == 6) {
			aux = true;
			break;
		} // there is not goto statement
	}
	if (aux) break;
}
1 Like

By the way, I think you have a problem with the curly brackets inside the inner loop and/or the if

Yes, JavaScript provides exactly what you’re asking for, you can label loops and break out of them and jump to specific labels:

Note that use of labels is extremely uncommon and if you’re trying to use them be aware there are other methods of structuring the code that do not involve goto-like constructions. Even use of break/continue is a relative rarity in production JS codebases. Function calls are normally how you should deal with this.

If, in a job, on a real codebase, you write code that makes use of labels: a. the code quality tools that check the JS for issues (depending how they are set up) will, at best, start throwing warnings, and at worst, prevent your code from compiling, b. no-one who reads the code will know what you’re doing.

Labels work just fine, just nobody really uses them because nobody really writes code like that (in part because goto is a thing that’s been removed from most modern languages; JS has no goto but I’m surprised even labels are still in the language)

3 Likes