yossi
yossi

Reputation: 1431

I don't understand the Scope

1 - why when I run the below code I got undefind instead "a=1" ?

function f1(){a=1; f2();}
function f2(){return a;}
var a= 5;
a = f1();
​alert(a);​

like this example the resualt is "a=1".

function f1(){a=1; f2();}
function f2(){alert(a);}
var a= 5;
f1();

Upvotes: 2

Views: 91

Answers (7)

Bergi
Bergi

Reputation: 664297

With

a = f1();

you are assigning the result of calling f1 to a. Yet, f1 does not return anything, it evaluates to undefined. You'd need to use a return statement:

function f1(){a=1; return f2(); }

Btw, this is not a scope problem. You don't have any variables that are local to your functions, everything accesses the same a.

Upvotes: 6

Aelios
Aelios

Reputation: 12137

You probably forget a return statement to get your a value

function f1(){a=1; return f2();}
function f2(){return a;}
var a= 5;
a = f1();
​alert(a);​

Upvotes: 1

timidboy
timidboy

Reputation: 1722

f1() doesn't return any value. Returning nothing is the same as returning undefined.

Upvotes: 0

W3t Tr3y
W3t Tr3y

Reputation: 402

During the line a = f1(); the f1 function isn't returning anything so a is getting set to undefined.

I'm not positive what you are trying to do; if you add more I could make a suggestion for how to make it do what you want.

Upvotes: 0

Vytalyi
Vytalyi

Reputation: 1695

function f1 in 1st example did't returns any value, so that is the reason

Upvotes: 0

pdoherty926
pdoherty926

Reputation: 10349

You need to explicitly return from f1.

Upvotes: 0

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

f1 does not return anything that's why try the below

function f1(){a=1; return f2();}
function f2(){return a;}
var a= 5;
a = f1();
​alert(a);​

even if does not make lots of sense

Upvotes: 1

Related Questions