Perils of Omitting “var”
Note: This was originally posted on my blog at https://therobinkim.com/blog/perils-of-omitting-var. Any updates will appear there and not here.
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!