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

Why does an arrow function works and a function expression doesn't?

Hello,

I wrote the function to get a random RGB value as a function expression with a return command. This is not working for me:

let html = ''; let i = 0 let randomColor = function() { Math.floor(Math.random() * 256); return randomColor; };

function getRGB() { const color = rgb(${randomColor()},${randomColor()},${randomColor()}); return color }

If I change the same function to an arrow function as Mr. Guil did in the solution video, like this:

let randomColor = () => Math.floor(Math.random() * 256);

then the code starts working. Why is this? Is there a problem with my function expression or can't expressions be used for this situation?

Thanks for your help.

2 Answers

Hi Zaid,

Thank you for your answer. I get it now.

Hi Mila Capecchi

It does work, you just don't return randomColor because you are storing your function in that variable. return what's inside the function.

Like this:

let randomColor = function(){
     return Math.floor(Math.random() * 256);
}

function getRGB() { 
  const color = `rgb(${randomColor()},${randomColor()},${randomColor()})`; 
  return color; 
}
  console.log(getRGB());

Also, it's a good practice to wrap your code around 3 backticks ``` Like the way I did. It's much easier to understand the code.