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

Aaron Jones
Aaron Jones
637 Points

can't figure out this question

create a new function named max which accepts two numbers as arguments (you can name the arguments, whatever you would like). The function should return the larger of the two numbers.

HINT: You'll need to use a conditional statement to test the 2 parameters to see which is the larger of the two.

script.js
function max (24,12) {
  var largerNumber = math.ceil (24, 12);
  return largerNumber;
}

1 Answer

Hi,

Math.ceiling is not an appropriate use case here. Basically, what the project wants you to do is to define a function which accepts two parameters, both of which are numbers. The function should then check which of the two is the larger number and return that number.

IF YOU DON'T WANT TO SEE THE SOLUTION, DON'T SCROLL DOWN!

function max(firstNumber, secondNumber)
{
  if (firstNumber > secondNumber)
  {
    return firstNumber;
  }
  return secondNumber;
}

My function accepts two parameters which are stored in the variables firstNumber and secondNumber, respectively. I then test to see if firstNumber is larger than secondNumber. If it is, I return that number. If it isn't, I return the second number. Notice I used only one if statement. That's because we only have two numbers and thus two possibilities. If the code continues to execute past the first if statement after we have checked to see if firstNumber is larger, then the only answer left is to return secondNumber. Once a return statement is hit, code execution stops, so I don't have to explicitly list the second test case in a conditional statement.

Remember that you don't want to hard code your 24 and 12. You want them to be variable names so that when someone calls the function, they can use whatever number combination they want and still get an answer. If you use variable names, the function is reusable.