0

In a Javascript file, how can I tell to stop run the rest code?

For example,

if (typeof $==="undefined") return;

return doesn't work as it can only be used in a function.

I don't want to throw an exception either.

  • I don't think this is possible. – Marco Mar 15 '23 at 23:43
  • _"I don't want to throw an exception either"_... why not? – Phil Mar 15 '23 at 23:43
  • 2
    wrap the whole code in an IIFE ... or ... `if (typeof $ !== "undefined") { rest of code here }` – Jaromanda X Mar 15 '23 at 23:45
  • I prefer to always have at least a `main` function. – jabaa Mar 15 '23 at 23:46
  • It's not duplicate.answers on the other question can't do it. It seems the conclusion is it's not possible without using throw. I don't want to use throw as it'll throw an exception which it isn't. I return it on purpose. –  Mar 16 '23 at 00:55
  • The trick is to prevent reporting the throw, shown as `window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);` in the accepted answer of the duplicate. Note `throw` doesn't need to throw an exception, it can throw any value you want, including one that a try/catch block around `main` could identify, suppress global error reporting and rethrow another (or same) value to return to the event loop. – traktor Mar 16 '23 at 01:27

0 Answers0