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

JavaScript JavaScript Functions Create Reusable Code with Functions Using Multiple return Statements

Is it ok to get undefined?

Is it ok to get undefined if a function doesn't get called right away?
Like in the console I get the following...

function add(num1, num2) {
var total = num1 + num2;
return total;
}
undefined

But if I call the function straight away and add arguments I get without undefined displayed in the console.

function add(num1, num2) {
var total = num1 + num2;
return total;
}
add(2, 5);
7

Please note I'm using var instead of const as the console keeps variables in memory for a long time.
Thanks

1 Answer

If you declare a function in a script file it wont be called until you actually call it, when you run it in your browser console it calls it right away with no arguments sort of predictively, causing undefined, and gives you the result when immediately called with arguments.

Hope that helps.