Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit javascript script tags early?

I have a page with a bunch of .... sections. In one of them, I get half way through it and decide I want to stop, and not run the rest of the contents of this script tag - but still run the other code segments on the page. Is there any way to do this without wrapping the entire code segment in a function call?

for example:

<script type='text/javascript'>
    console.log('1 start');
    /* Exit here */
    console.log('1 end');
</script>
<script type='text/javascript'>
    console.log('2 start');
    console.log('2 end');
</script>

which should produce the output

1 start
2 start
2 end

and NOT 1 end.

The obvious answer is to wrap the script in a function:

<script type='text/javascript'>
    (function(){
        console.log('1 start');
        return;
        console.log('1 end');
    })();
</script>

Although this is usually the best approach, there are cases where it is not suitable. So my question is, what OTHER way can this be done, if any? Or if not, why not?

like image 395
Benubird Avatar asked Sep 27 '22 17:09

Benubird


1 Answers

You can use the break statement :

breakCode : {
  document.write('1 start');
  /* Exit here */
  break breakCode;
  document.write('1 end');
}

With a label reference, the break statement can be used to jump out of any code block


Reference

  • break MDN
like image 70
R3tep Avatar answered Oct 03 '22 02:10

R3tep