How do I exit javascript script tags earlier?

I have a page with a bunch of .... sections. In one, I get halfway through it and decide I want to stop and don't run the rest of the content of that script tag, but still execute other segments of code on the page. Is there a way to do this without wrapping the entire code segment in a function call?

eg:

<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 output 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>

      

While this is generally the best approach, there are times when it doesn't work. So my question is, what ELSE way can be done, if any? Or if not, why not?

+3


source to share


2 answers


You can use the break statement:

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

Run codeHide result


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




Link

+2


source


One way to achieve what you want (stop execution of a given script block, without wrapping it in a function) is to throw an error.

<script type='text/javascript'>
    console.log('1 start');
    throw new Error();
    console.log('1 end');
</script>

      



Of course, the downside to this is that it will result in an error being logged to the console.

0


source







All Articles