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

Jeremy Yochum
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jeremy Yochum
Front End Web Development Techdegree Graduate 16,023 Points

Why do you not include parentheses when passing a function as an argument?

When passing a function declaration as an argument into another function why are the parentheses unnecessary? Do you not need to call the function to pass it as an argument? From my understanding of functions (which is limited), a function call without a set of parenthesis will cause a syntax error.

Here is the working code:

let html = '';

function random(){
  return 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(**random**)}">${i}</div>`;
}

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

So why does the previous code work but not this?:

html += `<div style="background-color: ${randomRGB(**random()**)}">${i}</div>`;
}

1 Answer

Steven Parker
Steven Parker
229,657 Points

The parentheses are only used if you want to call the function first, and then pass the return value from it as an argument. Parentheses are not used when you pass a reference to the function itself as the argument.

Here, the random function is being passed to randomRGB, which then calls it three separate times while it runs (as value()) to get different values for each color.

Jeremy Yochum
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jeremy Yochum
Front End Web Development Techdegree Graduate 16,023 Points

I see, so basically if you are not calling the function to receive a return value then you can use a reference to the function, similar to a variable. Thanks, I understand now.