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 trialMila Capecchi
4,429 PointsWhy 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
Mila Capecchi
4,429 PointsHi Zaid,
Thank you for your answer. I get it now.
Zaid Khan
12,769 PointsIt 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.