Why does it say my variable c is undefined when I returned it? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does it say my variable c is undefined when I returned it?

https://code.sololearn.com/Wa63fJ8TTbGC/?ref=app

10th May 2017, 3:12 AM
AceDev
2 Answers
+ 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.
10th May 2017, 3:29 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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++"));
10th May 2017, 8:22 AM
visph
visph - avatar