辛夷坞

涧户寂无人,纷纷开且落

By - Christen

JavaScript Variable Statement

What is the difference between

var a = 1;

and

b = 1;

?
From: Mozilla Developer Network

var
The variable statement declares a variable, optionally initializing it to a value.
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are:
1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

function x() {
  y = 1;   // Throws a ReferenceError in strict mode
  var z = 2;
}
x();
console.log(y); // logs "1"
console.log(z); // Throws a ReferenceError: z is not defined outside x

2. Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.

console.log(a);                // Throws a ReferenceError.
console.log('still going...'); // Never executes.
var a;
console.log(a);                // logs "undefined" or "" depending on browser.
console.log('still going...'); // logs "still going...".

3. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

var a = 1;
b = 2;
delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise.
delete this.b;
console.log(a, b); // Throws a ReferenceError.
// The 'b' property was deleted and no longer exists.

Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus it is recommended to always declare variables, regardless of whether they are in a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable throws an error.

Leave a Reply

Your email address will not be published.
*
*