Skip to content Skip to sidebar Skip to footer

Undeclared Variables Usage In Javascript

Why does JavaScript throw a reference error if we try use a variable which is not declared but allows to set the value for the same ? e.g a = 10; //creates global variable a and se

Solution 1:

That's just how the language works. In non-strict mode, an assignment to an undeclared symbol is implicitly treated as creating a global variable. In strict mode, that's an error.

To use strict mode, a global script block or a function should start with the statement:

"use strict";

That is, a simple expression statement consisting of the string "use strict". That will prevent the accidental creation of global variables (which can still be created explicitly), and impose a few other restrictions.


Solution 2:

According to the documentation:

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.

  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...".
  1. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

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.


Solution 3:

a = 10;
internally declares var a i.e. in background it first declares the variable globally and then set the value for that variable.

So whenever we write a=10 what actually happens:
var a;
a=10;
hence a is never undefined;

but alert(b) in this case b has no values defined so it remains undefined

And as Pointy said,

In non-strict mode, an assignment to an undeclared symbol is implicitly treated as creating a global variable. In strict mode, that's an error.

Its always a better practice to use use strict


Post a Comment for "Undeclared Variables Usage In Javascript"