A simple solution to this problem is to wrap any code that you don’t want in the global scope in an immediately-invoked function expression (IIFE). All the variables assigned in the function’s scope are deallocated when the function ends:
(function() {
// Put your code here...
})();
For more info on IIFEs: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
[Update]
In ES6 you can use blocks (so long as you use let
instead of var
):
{
// Put your code here...
}
For more info on blocks: http://exploringjs.com/es6/ch_core-features.html#sec_from-iifes-to-blocks