Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

Tim Callan
Tim Callan
23,598 Points

What is calling the function in this code?

I just finished JavaScript Basics and in it we learned to call a function such as : function example(a,b) { doSomething; }

example();

Now I'm working through the Loops, Arrays and Objects in workspaces and I come across the following example:

function randomNumber(upper) { return Math.floor( Math.random() * upper ) + 1; } var counter = 0; while ( counter < 10) { var randNum = randomNumber (6); document.write(randNum + ' '); counter+= 1; }

The code runs perfectly but I'm not sure of what "called" the function. I would have expected to see a line such as: randomNumber(75); to call it. Is the variable randNum somehow calling it? Any help would be appreciated. Thanks.

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,545 Points

Hi Tim,

It is the variable called randNum that is calling the function (kind of).

In the line var randNum = randomNumber (6); the function is being called with the argument 6 being passed in, and then the result (return) on the function call is being stored in the randNum variable. It's almost best to read that line backwards. Function is called -> then result is returned -> then it's stored in a new variable we have defined.

I hope that makes sense.

Keep Coding! :)

Tim Callan
Tim Callan
23,598 Points

Hi Jason, That does make sense! Thank you for your quick reply. Tim