What is the best practice to run several unrelated scripts in the same file?

I know that JavaScript files can be fragile in the sense that if a user has two or more unrelated scripts in the same file, an error in the first codepiece could cause the second codepiece not to run (the interpreter would just stop running, never reaching to the second one) or an error in the second codepiece could cause the third codepiece not to run (the interpreter would just stop running, never reaching the third one), etc.
This is something I could name as a local error.

If I am not mistaken, at least in some cases, even having a mistake in whichever of the codepieces would prevent the entire program from running because JavaScript is somewhere in the middle between “interpreted” and “compiled”.
This is something I could name as a global error.

If what I have just described is correct and at least about the first type of cases (local error), how to cope with that?
How to make sure that although one file has two or more codepieces, each codepiece would be treated as “separate” or “pseudo file” and the interpreter would go from top to bottom even if there is at least one local error above some codepiece?

You can put all your JavaScript code between

(function () {
   // Code goes here
})();

in each js file that way no variable or functions will cause conflicts.

Alright, then I assume that codes with an arrow function as follows are also good

window.setTimeout( ()=>{
    // Do stuff
}, 1);

window.setInterval( ()=>{
    // Do stuff
}, 1);

window.addEventListener('EVENT_NAME', ()=>{
    // Do stuff
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.