2

I was wondering if there was a way to break javascript execution, something like this

<script>

if(already_done)
{
  return; //prevent execution (this yields an error)
}

doSomeStuff();

</script>

I know that this is possible like this:

<script>

if(already_done)
{
  // do nothing
}
else
{
  doSomeStuff();
}
</script>

But it's not the solution I'm looking for.

Hopefully this makes sense.

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232

5 Answers5

7

Wrap it in a function which immediately executes.

(function() {

    if (already_done) { return; }

    doSomeStuff();

})();

FYI: return is useless without being in a function context.

Also, this isn't a closure since it doesn't return an inner function which uses variables defined in an outer function.

Community
  • 1
  • 1
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
3

Put your code in a closure, like this:

(function (){

  if(already_done){
    return;
  }

  doSomeStuff();
})();

It should work.

szanata
  • 2,402
  • 17
  • 17
  • 1
    This isn't necessarily a closure, it is an anonymous function though. – Nick Craver Oct 25 '10 at 18:41
  • @Nick Craver: When is it *not* a closure? – Tomalak Oct 25 '10 at 18:43
  • 2
    @Tomalak: A closure is when you return a function inside of another function, and in the inner function you're binding variables defined in the outer function per http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work – meder omuraliev Oct 25 '10 at 18:45
  • @Tomalak - when nothing inside is it exposed to the outside, creating a linkage of sorts between internal an external members, "closing" off part of it, e.g. if it had `window.var = somethingInHere` and that referenced other things, it'd be a closure. There's often confusion around this, Closure != scoping != anonymous method, there's a lot of overlap, but they're not synonymous. – Nick Craver Oct 25 '10 at 18:46
  • @Nick Craver, @meder: Okay, fair enough. – Tomalak Oct 25 '10 at 18:51
3

You have one option directly in a <script> block: you can throw an error, but this usually isn't desirable in the middle of a block of code...

if(already_done){
  throw "Uh oh";
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
0

What would 'already_done' be? a boolean? it sounds to me like a loop... can you use something like?:

While ( !already_done ) { doSomeStuff(); }

Josmas
  • 147
  • 4
0

You could use break with a label:

<script>

testcase:
if (already_done) {
    break testcase; //prevent execution
}

doSomeStuff();

</script>

though, as stated in other answers, wrapping it in a function is your best method.

drudge
  • 35,471
  • 7
  • 34
  • 45