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 Basics (Retired) Creating Reusable Code with Functions Create a max() Function

Benjamin Lowry
Benjamin Lowry
7,941 Points

clarification on functions with conditional statements

I kept getting this challenge wrong because I was using {} within the conditional statement in the function. So...when you use a conditional statement that is nested within a function you don't use the {}? I'm sorry if this is not clear enough to get a concise answer, I can post more in detail if needed.

script.js
function max(lower, upper) {
  if (lower > upper)
    return lower
  else 
    return upper
}
alert( max(20, 60) );
Nestor Alonso
Nestor Alonso
11,428 Points
function max(lower, upper) {
  if (lower > upper) {
    return lower;
   } else {
    return upper;
   }
}

The conditional statement needs {} to work properly, how did you had it?, maybe it was a syntax error.

Benjamin Lowry
Benjamin Lowry
7,941 Points

Yes but notice how in my code I do not have the curly braces after the if and else keywords that enclose the return values, only at the beginning and end of the entire function, which includes the conditional statement. When I tried to run the code with the curly braces like you have them..i got an error each time.

That is what I am confused about, they way you have it is the way I thought it should be.

1 Answer

Steven Parker
Steven Parker
231,096 Points

Braces are required when there is more than one statement in the conditional.

If you have only one statement, the braces are optional. Because in this function there is only one statement for each condition, your code is fine. But so is Nestor's. Both versions pass in the challenge.