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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

Tim Callan
Tim Callan
24,230 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,858 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
24,230 Points

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