PseudoSavant

The Musings of Paul Ellis

  • About me
  • JS 101: Global Variables

    javascript-icon.pngUnderstanding global variables and scope is very important in JavaScript. Misunderstanding what a variable’s scope is can lead odd bugs and broken code. This is made more problematic because the default scope in JavaScript is global. But what is global and how should you use it?

    In JavaScript all code uses the same ‘global’ scope. The global scope is actually just a reference to the top-most object in the scope chain. On browsers the global object is `window`. Other environments, like node.js, have a different global object though.

    Global Variables

    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 global

    Filed In: Uncategorized
    January 29, 2014
  • Subscribe via Email

    Enter your email address to receive new posts to this blog in your inbox. I'll never mail anything else. Seriously.

  • Links

    • GitHub
    • Homemarks
  • Recent Posts

    • Meta “When is it stealing?” Inception.
    • Craftsman
© 2026 J. Paul Ellis