0
Why does it say my variable c is undefined when I returned it?
2 odpowiedzi
+ 7
The main reason is because variable c is a local variable of the function and cannot be invoked outside the function. This is how I altered your code:
function hippy(one, bleh)
{
var c = (one+ "is better than "+bleh);
return c;
}
str = hippy("js", "c++");
alert(str);
console.log(str);
Now, we return the local variable c to a global variable str, and console.log the global variable.
+ 7
@AceDev:
You seems to have modified your code by following @Hatsy Rei advice... but you do too much: it's not necessary to do same with your two other functions ;P
function hi(){
/*
var a= alert("howdy") ;
return a;
*/
alert("howdy") ;
// is enough, as your function call expect only a behaviour, not a returned value
}
hi(); // by calling this function, you will just alert("howdy") you doesn't store a value if one is returned ;)
function foo (boo){
// same here
/*
var b = alert(boo + "is fun!") ;
return b;
*/
alert(boo + "is fun!") ;
}
foo("Js ");
function hippy(one, bleh){
var c = alert(one+ "is better than "+bleh) ;
return c;
}
hippy("js", "c++"); // with this you don't store the returned value
// and you still cannot access the 'c' variable... look better at @Hatsy Rei code:
// console.log(c);
var result = hippy("js", "c++"); // with this you store the returned value
// and you log it:
console.log(result);
But anyway, the returned result isn't really interresting: it's the returned value of alert() function, wich return nothing ^^
So, maybe you are attempting to rather do:
function hippy(one, bleh){
var c = one+ "is better than "+bleh ;
return c;
}
var r = hippy("js","c++");
alert(r);
// or shortener:
alert(hippy("js","c++"));