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

Anusha Singh
PLUS
Anusha Singh
Courses Plus Student 22,106 Points

I can't understand this question:- I typed { function max(a, b) { if(a > b) { return a; } }

Can you help me with how can I return the number for this

script.js
function max(a, b) {
  if(a > b) {
   return a;
  }

}

3 Answers

anil rahman
anil rahman
7,786 Points

You are correctly doing the check but the only thing you are missing is what to do when b is larger than a so basically an else clause.

function max(a, b) {
  if(a > b) {
   return a;
  }
  else{
   return b; 
  }

}

alert(max(1,2));
anil rahman
anil rahman
7,786 Points

Another way is this which is probably the better option than my first.

function max(a, b) {
  if(a > b) {
   return a;
  }

  return b; 


}

Also you can do this:

function max(a, b) {
  var result;
  if(a > b) {
    result = a;
  }
  else{
    result = b;
  }
  return result;


}
brandonlind2
brandonlind2
7,823 Points
function max(a, b) {
   var A;
  if(a > b) { A= a;}
   return A;
}
anil rahman
anil rahman
7,786 Points

The return can be used within the if which is the correct the way for this question. Which i have posted above :)

brandonlind2
brandonlind2
7,823 Points

I didnt know that buts thats nice to know

brandonlind2
brandonlind2
7,823 Points

I didnt know that buts thats nice to know