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

Exercice with function and condition statement

I begin and I am blocked with this exercice :-( 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(1, 2) {

  if (2 > 1) { 
   var larger = 2;
  };

  return larger; 
}

2 Answers

Dave Harker
PLUS
Dave Harker
Courses Plus Student 15,510 Points

Hi Vanessa,

I suspect it is because you're passing in two integers directly instead of arguments as the task wanted. Try something like this perhaps:

function max(numberOne, numberTwo) {
  if( numberOne > numberTwo) return numberOne;
  else return numberTwo;
}

Another issue is that 1 could never be returned in your code, only 2 (assuming they could be passed that way). To get that code working you might change it to something like:

function max(num1, num2) {
  var larger = num1; // define/assume num1 is larger initially

  if (num2 > num1) { 
   larger = num2; // if num2 is larger then assign it to the 'larger' variable
  };

  return larger; 
}

Great effort though. Keep going!

Dave.

Thanks a lot Dave, it works !