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

Tony Shangkuan
Tony Shangkuan
7,200 Points

How does value() & randomRGB(randomValue) work in this case

This is an course link

let html = '';
const randomValue = () => Math.floor(Math.random()*256);

function randomRGB(value) {
  const color = `rgb( ${value()}, ${value()}, ${value()} )`;
  return color;
}

for (let i=1; i<=10; i++) {
  html += `<div style="background-color: ${randomRGB(randomValue)}">${i}</div>`;
}

document.querySelector('main').innerHTML = html;

two questions:

  1. randomValue() is function but does not have () in randomRGB(randomValue)
  2. value is not a function but is used as a function value() in rgb( ${value()}, ${value()}, ${value()} )

1 Answer

Steven Parker
Steven Parker
231,172 Points

Last January, someone asked this very similar question. I'll repeat my answer here:

When randomRGB is called in the main program, the argument passed to it is randomValue, which is the name of a function. So for the duration of the randomRGB function, the parameter name "value" is equal to "randomValue", which means it can be called as a function.

When a function reference is passed as an argument to another function, this is often referred to as a "callback". And when passing a function reference, the parentheses are not used. If they were, the function would be called immediately and the return value would get passed instead.

So the value() function is created every time randomRGB is called.

Tony Shangkuan
Tony Shangkuan
7,200 Points

Although I started to understand a bit better, I'm still a bit confused. Is there any course to further address the use of a function reference ?

Steven Parker
Steven Parker
231,172 Points

Perhaps the Callback Functions in JavaScript course is what you're looking for.