Reputation: 17193
My code:
f();
var a = {v: 10};
function f() {
console.log(a.v);
}
Gives the error that undefined
has no property v
.
However the following code works:
var a = {v: 10};
var f = function() {
console.log(a.v);
}
f();
Why doesn't the first version work?
Upvotes: 0
Views: 40
Reputation: 181
It's due to the order. When you call the function in the first version, then the json isn't defined. So it tries to get property of undefined object.
So it is necessary to call the function after declaring the object.
Upvotes: 0
Reputation: 288260
Hoisting moves function declarations and variable declarations to the top, but doesn't move assignments.
Therefore, you first code becomes
var a;
function f() {
console.log(a.v);
}
f();
a = {v: 10};
So when f
is called, a
is still undefined
.
However, the second code becomes
var a, f;
a = {v: 10};
f = function() {
console.log(a.v);
};
f();
So when f
is called, a
has been assigned.
Upvotes: 4