The problem described above is typical for any programming language. The so-called modules are used as a solution.
A module is a kind of construction, made in such a way that the variables and functions of this construction are visible only inside it and don't interfere with anyone outside.
There are several types of modules in JavaScript. The simplest - modules via closures are created by in-place function call, like this:
;(function() {
// here is a module code
})();
Variables and functions created in such a module will not be visible outside of that module:
;(function() {
let str = 'a module variable';
function func() {
alert('a module function');
}
})();
// Here the variables and functions of the
module are not available:
alert(str);
alert(func);