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 Functions Arrow Functions Function Challenge Solution

If statement syntax inside arrow functions

When trying to find the solution on my own, I used the code below based on what's been taught in previous lessons but I get a console error that says "Uncaught SyntaxError: Unexpected end of input." in regards to the last line.

If I follow the solution and remove "else {" it suddenly works. Why is that? I thought those were needed for an if statement to work.

const randomNumber = (lower, upper) => {
  if ( isNaN(lower) || isNaN(upper)) { 
   console.log( `Please enter a number. You input a string.` ); 

} else { 
   return Math.floor(Math.random() * (upper - lower + 1)) + lower;
};

// Call the function and pass it different values.

  console.log( randomNumber( 5, 10) );

1 Answer

Steven Parker
Steven Parker
231,275 Points

The video solution uses a "throw" when an error is made instead of "console.log". The "throw" causes the function to end so no "else" is needed.

You need the "else" here because the function keeps running after logging.

I should've added this when I first posted my Q but that code is returning an error for the last line. The error is "Uncaught SyntaxError: Unexpected end of input."

Do you know why that is? I thought if statements needed "else {" in order to work.

Steven Parker
Steven Parker
231,275 Points
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
  }  // <-- this brace to close the "else" was missing
};    // <-- this brace ends the function

And an "else" is entirely optional for the syntax (though sometimes it may be needed for the program logic to work).