It is considered a best practice to avoid 'polluting' the global scope with variables that are intended to be local to the script. Global variables created from a script can produce name collisions with global variables created from another script, which will usually lead to runtime errors or unexpected behavior. It is mostly useful for browser scripts. Top-level declarations in ES modules and CommonJS modules create module-scoped variables.
var foo = 1;
function bar() {}
// explicitly set on window
window.foo = 1;
window.bar = function() {};
// intended to be scope to this file
(function() {
let foo = 1;
function bar() {}
})();
// correct code for ES Modules
// foo and bar are local to module
let foo = 1;
function bar() {}