1

I have a loop in Javascript, I want to run console.log() in a specific iteration, and then terminate. What is the best method to go about doing this?

I'm wanting something like Perl's

die Dumper \@foo;
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • 1
    possible duplicate of [JavaScript equivalent of PHP’s die](http://stackoverflow.com/questions/1361437/javascript-equivalent-of-phps-die) – Pekka Mar 09 '11 at 18:00

3 Answers3

2

You can throw an exception:

throw "Help I have fallen and cannot get up";

Not exactly the same, but (in my experience) it's not too common to see exception handling in ordinary DOM-wrangling sorts of JavaScript code, so that usually will blow out of any event loop. However, it's not really the same thing as any surroundling try block will catch what you throw.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

you mean terminate loop?

while(true) {
console.log()
if(condition) {break};
}

the break command exits the loop

but there is no kill or exit function in javascript.

Gergely Fehérvári
  • 7,811
  • 6
  • 47
  • 74
0

Since JavaScript is event-based, a script doesn't control when it terminates — there's no die or exit.

If it's not one already, the best option is to refactor the code into a function that you can return from, or use a named block:

foo: {
    // do work
    break foo;
    // not executed;
}
s4y
  • 50,525
  • 12
  • 70
  • 98