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 Working with 'for' Loops The Refactor Challenge – Duplicate Code

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,430 Points

An observation...

This isn't really a question. It's more of an observation.

This statement doesn't really do anything.

const random255 = () => Math.floor(Math.random() * 255);

If I print the value of random255 to the console:

console.log(random255);

I get this: () => Math.floor(Math.random() * 255).

It does not become a function until the () are added.

This is what let Guil pass the inner workings of the function as a variable to another function and then run them multiple times independently.

I didn't understand why passing one argument resulted in three different numbers.

Fascinating!

1 Answer

Steven Parker
Steven Parker
218,596 Points

It is a function, but it is not invoked ("called") until you add the braces. When you pass a callback, you don't want to invoke it yet, you only want to pass the function by name so the other function you pass it to can do the calling later.

The statement that didn't seem to do anything actually defines the function. It could also be written like this:

function random255() { return Math.floor(Math.random() * 255); }

Does it make more sense now?

Stephen Cole
Stephen Cole
Courses Plus Student 15,430 Points

I think you misunderstood my comment.

I think that it's interesting how the variable random255 stores the code of the function instead of invoking a function three times.

He could have created--as you did--a function and then called it three times. Instead... by passing the variable with code inside it. He added the () to make it become a function.

console.log(random255);

returned the code () => Math.floor(Math.random() * 255)

console.log( random255() )

ran the function.

Guil created a function and passed the value of the arrow function expression multiple times.

Sort of like colors(random255) and then, in the function used random255() to invoke it as many times as needed.

I just thought it was interesting.

Steven Parker
Steven Parker
218,596 Points

What might you have done instead?