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

16,697 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("The number was " + randomNumber + "<br />");
document.write(" It took the computer " + attempts + " attempts");

1 Answer

Steven Parker
Steven Parker
201,997 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".

16,697 Points

Oh okay, i understand now. Thank you!