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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With