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 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
229,577 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!