JavaScript

JavaScript

Made by DeepSource

Prefer not to declare variables in global scope JS-0067

Anti-pattern
Minor

It is considered a best practice to avoid 'polluting' the global scope with variables that are intended to be local to the script. Global variables created from a script can produce name collisions with global variables created from another script, which will usually lead to runtime errors or unexpected behavior. It is mostly useful for browser scripts. Top-level declarations in ES modules and CommonJS modules create module-scoped variables.

Bad Practice

var foo = 1;
function bar() {}

Recommended

// explicitly set on window
window.foo = 1;
window.bar = function() {};

// intended to be scope to this file
(function() {
  let foo = 1;
  function bar() {}
})();

// correct code for ES Modules
// foo and bar are local to module
let foo = 1;
function bar() {}