Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
brandonlind2
7,823 Pointswhy does this function return the value of its nested function
Why doesn't this work?, Functions are also values, so I'm not understanding why this isn't working.
function test(){
function test2(){
return 10;
}
return test2();
}
1 Answer
Michael Hulet
47,913 PointsIn this case, you're calling test2 and asking for its value, and it returns the value test2 hands back. If you want to return the function test2 itself, just remove the parentheses next to the return statement for test, like this:
function test(){
function test2(){
return 10;
}
return test2;
}
In JavaScript, writing the parentheses after a function's name tells the interpreter that you want the value the function returns, and not the function itself. Not using the parentheses tells the interpreter that you want the function itself
brandonlind2
7,823 Pointsbrandonlind2
7,823 PointsThanks for the reply, my goal is to have test, the parent function return 10, it keeps coming up as undefined for me for some reason.
Michael Hulet
47,913 PointsMichael Hulet
47,913 PointsIn that case, your original snippet works on my machine (Mid-2015 MacBook Pro, OS X 10.11.6 Beta 1, Safari Technology Preview 9.1.2)
Michael Hulet
47,913 PointsMichael Hulet
47,913 PointsIf you're trying this out in the console, when you define that function, it'll always say
undefinedafterwards when you finish typing it in, because the console successfully created that function and has nothing to say about it. Have you been trying to call the function afterwards? Is it still saying it'sundefined?brandonlind2
7,823 Pointsbrandonlind2
7,823 Pointshaha yeah that was it, thanks I was expecting the console to return 10 after a I typed it in, I didnt invoke it.