Any variable in the top-most global scope is considered a global variable. In the example below `a` is a global variable because it was defined at the top-most scope. Global variables are actually just properties of the global object. Which is why `a === window.a` is true.
Generally speaking it is best to limit the number of global variables you use so that you don’t pollute the global namespace. You can prevent variables from being global by enclosing your code in an immediately invoked function expression (IIFE). Variable declared inside the function will be scoped to just the function.
Variables declared without `var` are implicitly global even if it is declared inside an IIFE. It is considered bad practice to declare variables without `var`, especially since it could be declared that way on accident. Static code analysis tools like JSHint specifically will warn you about it.
Sometimes you’ll want to export some variables to the global namespace however. The example below shows a ‘good’ way to create global variables. I assigned the local variable `y` to a global variable `z` which I can now access anywhere.
Here are some other ways to create global variables:
Global variable in any environment
Export functions to globalFiled In: UncategorizedJanuary 29, 2014