How to avoid global variables in JavaScript?

To avoid global variables in JavaScript, define them inside a self-executing function like so: (function() { ... })().

Here's how you do it:

(function() {
  var localVariable = 123;

  console.log(localVariable); // 123
})();

var globalVariable = 'Hello World!';

console.log(globalVariable); // Hello World!
console.log(localVariable); // Uncaught ReferenceError: localVariable is not defined