Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,149 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
216,149 Points

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

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