Differences Between Declaring Variables with and without var
in JavaScript
Category Programming Techniques
When declaring variables in JavaScript, using the var
keyword and not using it often results in no runtime issues, but there are differences between the two methods. Code that runs correctly does not necessarily mean it is well-written.
var num = 1;
This declares a variable in the current scope. If declared inside a function, it is a local variable; if declared in the global scope, it is a global variable.
Whereas
num = 1;
is actually an assignment operation to a property. It first attempts to resolve num
within the current scope chain (e.g., if declared in a function, the scope chain includes the global scope and the function's local scope, etc.). If num
is found in any part of the current scope chain, it assigns the value to the num
property. If num
is not found, it creates the num
property on the global object (the top-level object in the scope chain, such as the window
object) and assigns the value.
Note! This does not declare a global variable but creates a property on the global object.
Even so, you might still find it difficult to understand the difference between "variable declaration" and "creating an object property." In fact, JavaScript's variable declarations, property creations, and each property in JavaScript have certain flags that describe their attributes—such as ReadOnly, DontEnum, DontDelete, etc.
Since variable declarations come with the DontDelete attribute, comparing var num = 1
with num = 1
, the former is a variable declaration with the DontDelete attribute and cannot be deleted; the latter is a property of a global variable and can be deleted from the global object.
// num1 is a global variable, num2 is a property of window
var num1 = 1;
num2 = 2;
// delete num1; cannot be deleted
// delete num2; can be deleted
function model(){
var num1 = 1; // local variable
num2 = 2; // property of window
// anonymous function
(function(){
var num = 1; // local variable
num1 = 2; // inherits scope (closure)
num3 = 3; // property of window
}())
}
PS: In the ECMAScript 5 standard, there is a "strict mode." In strict mode, assigning a value to an undeclared identifier will throw a ReferenceError, thus preventing the accidental creation of global object properties. Some newer versions of browsers already support this.