Aviv Cohn
Aviv Cohn

Reputation: 17193

Cannot reference script-level variable in function?

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

Answers (2)

D3myon
D3myon

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

Oriol
Oriol

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

Related Questions