5

My goal is to:

if(error){
    window.location.href = "error.htm";
    //end of every thing
}

What's more, return false wouldnt help because there may be functions inside of functions. My current solution is throw, but i feel uncomfortable

Any better idea || solution ??

rhapsodyn
  • 3,272
  • 5
  • 29
  • 36

2 Answers2

0

If you don't want to leave a function, I suppose you try to break for a loop.

Then you can use break :

function testBreak(x) {
   var i = 0;
 
   while (i < 6) {
      if (i == 3) {
         break;
      }
      i += 1;
   }
   return i * x;
}

(MDN example)

If you're trying to exit from more than one function, trough several stack call levels, then the only "valid" use case that comes to mind is the "exceptional" error, which can be handled with try/catch/throw as you saw. But abusing exception lead to hard to maintain code and often hides the errors. If you need it, your code probably doesn't really look javascript-esque.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

I use throw for exiting JS

throw new Error("my error message");

as described at ;

JavaScript equivalent of PHP’s die

Community
  • 1
  • 1
Erdinç Çorbacı
  • 1,187
  • 14
  • 17