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?
source to share
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.
source to share