0

In javascript, compilation phase find and associate all declarations with their appropriate scopes.

CASE1

a = 2;
console.log(a);

If not used in strict mode the snippet is assumed to be actually processed as:

var a;
a = 2;
console.log(a);

Output: 2

CASE2

if the declaration happens below console.log()

  console.log(a); 
  var a = 2;

Here at line 1: compiler will check for the declaration of a in its scope if not found, the global scope will assign one and the same code will be assumed again same as

   var a; 
   console.log(a);
   a = 2;

Output : undefined // as no value is assigned while interpreter read console

CASE3

 console.log(a); 
 a = 2;

Output: RefErr

Why this throws reference error and not undefined?

1

2 Answers 2

1

If you carefully look at your first two cases, you are always declaring the variable a, and in JavaScript only the declarations are hoisted.

That being said, in your Case 3, variable a is never declared, hence, hoisting is not possible here. With that, there is no variable by the name a in the scope, and hence, ReferenceError.

If you look at the description of ReferenceError, it reads:

The ReferenceError object represents an error when a non-existent variable is referenced.

1

Implicit globals do not imply a var statement. There is no hoisting of them.

Not the answer you're looking for? Browse other questions tagged or ask your own question.