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

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 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
231,109 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,809 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
231,109 Points

What might you have done instead?