Bar Akiva
Bar Akiva

Reputation: 1219

What is the difference between Uncaught ReferenceError and undefined?

In the following code, there are two instances of "undefined":

A:

b();
console.log(a);

var a = "Hello World!";

function b() {
 console.log("Called b!");    
}

This causes the console to show "Undefined" for "a".

B:

b();
console.log(a);

function b() {
 console.log("Called b!");    
}

This creates "Uncaught ReferenceError: a is not defined". In both cases a is undefined, and the console tells you that. But why does it choose to do it in different ways depending on the context? Are there a couple forms of "undefined" besides undefined and null?

Upvotes: 8

Views: 2747

Answers (2)

Tushar
Tushar

Reputation: 87233

The first code is treated as follow, because of hoisting.

var a; // Declare the variable

// Move function definitions to the top
function b() {
    console.log("Called b!");
}
b();
console.log(a); // Undefined, no value assigned yet

a = "Hello World!";

console.log(a); // Hello World!

In the second code a is never defined. And trying to access such variables will result in throwing ReferenceError.

Here's a blog to read more about hoisting.

The simple rule is:

  1. If variable is declared and not assigned any value it's undefined
  2. If variable/function is not defined and attempting to use it will throw Reference Error

Upvotes: 14

Jav Rok
Jav Rok

Reputation: 331

It's all about hoisting.

Basically your A block gets interpreted by Javascript as:

// Variable is declared, but without a value (undefined)
var a;

b();
console.log(a);

a = "Hello World!";

function b() {
  console.log("Called b!");    
}

So that's why you get an error in the second case: variable a is not defined anywhere.

Upvotes: 4

Related Questions