0

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.

4
  • in the browser. Commented Nov 12, 2017 at 5:34
  • They both define global variables when placed at the topmost scope. Commented Nov 12, 2017 at 5:49
  • @stealththeninja , @ Aluan Haddad , My intention is to define global not as a property of window object , in ES5 Commented Nov 12, 2017 at 6:23
  • Namespaces I guess. Commented Nov 12, 2017 at 7:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.