Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Uncaught ReferenceError and undefined?

Tags:

javascript

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?

like image 307
Bar Akiva Avatar asked Mar 04 '16 15:03

Bar Akiva


2 Answers

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
like image 74
Tushar Avatar answered Oct 06 '22 03:10

Tushar


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.

like image 39
Jav Rok Avatar answered Oct 06 '22 01:10

Jav Rok