As per my understanding , in ES6 we can define global variables in 2 ways
var global1 = '1'; // CASE 1
In this case "global1" is set as a property of DOM window object , so window.global1 will print "1".
let global2 = '2'; // CASE 2
In this case "global2" is NOT set as a property of DOM window object , so window.global2 will print undefined.
My question is how to achieve case 2 in case of ES5.
You can't. It is possible in ES6 because let
and const
declarations are stored in their own global environment that isn't tied to the global object. If you're working with ES5, that mechanism does not exist.
Generally global variables, in either approach, are frowned up on in JS codebases though. Ideally you's want to use a module system alongside Webpack to bundle up your code so that each file has its own scope, with things linked with explicit imports and exports.