This site runs best with JavaScript enabled.

Perils of Omitting "var"

Robin Kim

February 03, 2015


A JavaScript app will run whether you precede variable declarations with var. However, when you're creating new variables inside functions, omitting var will assign that variable to the global scope.

var sayGreeting = function() {
greeting = "hello";
};
console.log(greeting); // Uncaught ReferenceError: greeting is not defined
sayGreeting();
console.log(greeting); // "hello"

The above greeting is assigned to the global scope, hence is available outside the function after it is executed. (It throws an uncaught reference error before the function runs.)

var sayGreeting = function() {
var greeting = "hello";
};
console.log(greeting); // Uncaught ReferenceError: greeting is not defined
sayGreeting();
console.log(greeting); // Uncaught ReferenceError: greeting is not defined

This time, greeting is only accessible within the function. Attempting to access it outside the function will throw uncaught reference errors, whether or not the function runs.

The takeaway: Don't omit var when you create new variables. You're likely doing it wrong!

Share article