Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Getting Started With ES2015 Create Functions Using Arrow Syntax Concise Arrow Function Syntax

tomd
tomd
16,701 Points

Updating old code, arrow function doesn't work

I don't understand why this doesn't work. If you call functions in the same way then it should work.

var upper = 10;
var randomNumber = getRandomNumber(upper);
var guess;
var attempts = 0;

const getRandomNumber = upper => Math.floor(Math.random() * upper) + 1;

while (guess !== randomNumber){
  guess = getRandomNumber(upper);
  attempts += 1;
}
document.write(getRandomNumber(upper));
document.write("The number was " + randomNumber + "<br />");
document.write(" It took the computer " + attempts + " attempts");

1 Answer

Steven Parker
Steven Parker
215,370 Points

You should be aware that an arrow function isn't always a suitable replacement for a conventional function, see the MDN page for details.

But what's causing the trouble here is that an assignment is not hoisted like a conventional function definition would be. So the assignment of "getRandomNumber" needs to be done before you call it to create "randomNumber".

tomd
tomd
16,701 Points

Oh okay, i understand now. Thank you!