Reputation: 1431
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
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
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
Reputation: 1722
f1()
doesn't return any value. Returning nothing is the same as returning undefined.
Upvotes: 0
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
Reputation: 1695
function f1 in 1st example did't returns any value, so that is the reason
Upvotes: 0
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