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

Thaddeus Lorenz
Thaddeus Lorenz
3,434 Points

Need to know what specific code to fix

I've been stuck in a loop trying to get the first task to pass but it has been on and off. Can someone please help me by correcting my code?

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

3 Answers

Kevin Becerra
Kevin Becerra
14,243 Points

It needs to look something like this.

  function max(a, b){
  if( a> b){
  return a; 
  } else if (a < b){
  return b;
  }  
   }
Thaddeus Lorenz
Thaddeus Lorenz
3,434 Points

Thank you! Really appreciate it.

Steven Parker
Steven Parker
231,275 Points

This is not a good idea. What if a is equal to be? This code will return nothing in that case.

Nick Yoho
Nick Yoho
6,957 Points

Your if statement is correct, the issue is with the returns. Right now you're sort of telling the function to return the function within itself before its finished being defined. Just like how you're not saying max(a) > max(b) for the if, you don't need to say max() for the return.

Jonathan Dewitt
Jonathan Dewitt
8,101 Points

Adding a secondary if condition is redundant.

function max(a, b) {
    if (a > b) {
        return a
    } else {
        return b
    }
}
Steven Parker
Steven Parker
231,275 Points

For that matter, you don't need that else, either:

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