Javascript Globals and Variables

Global variables are bad in any language, Javascript is no exception. I've been reading and watching a lot of advance Javascript material lately and I learned something about Javascript global variables.


The Problem

You forget to declare a variable using var and if you are not using "use strict" it will declare it as a global variable if it's not being declared outside of the local scope.

Example #1

var year = 2015;
function setMonth() {
  month = "December" 
}
setMonth();
console.log(month); //outputs "December"

Example #2
In this example day is declared inside the function scope of setDay without using var. The compiler will check the outer scope which is setMonth and check there. Since it's not declared in the scope of setMonth it will check the outer scope of that, which is the global scope. Once it gets to the global scope then it will declare it as a global variable because it didn't find a declaration elsewhere.

var year = 2015;
function setMonth() {
  month = "December"
  function setDay() {
    day = "Monday";
  }
  setDay();
}
setMonth();
console.log(day); //outputs "Monday"

It's very easy to forget declaring your variables using var and it can happen to everyone but there things you can do.


The Solution

Invoke strict mode by placing "use strict" on top of your code. If you forget to use var the compiler will throw and error of undefined.

'use strict'
var year = 2015;
function setMonth() {
  month = "December"
}
setMonth();
console.log(month); //outputs "Uncaught ReferenceError: month is not defined"

Take it one step further by wrapping your code inside an IIFE.

(function(){
  'use strict'
  var year = 2015;
  function setMonth() {
    month = "December"
  }
  setMonth();
  console.log(month);
}());

I hope this is useful, don't forget to share!

Edgar Pino

About Edgar Pino

I’m a passionate software engineer working @ Pluralsight interested in distributed systems, machine learning, and the web. I am also a graduate student at the University of Illinois.

Comments