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?
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:
undefined
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With