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

what the wrong

what the wrong with this

script.js
/*Create a new function named max() which accepts two numbers as arguments. 
The function should return the larger of the two numbers.
You'll need to use a conditional statement
to test the 2 numbers to see which is the larger of the two.*/

function max(2,10){

  if(10>2){
  return y ;

  }  
}
    var x=2;
var y=10;
function max(2,10)

Hi Moath,

Replace the numbers in your function max definition and If statement with "x" and "y". Also, omit "function" in your final line and add a semicolon at the end of the statement.

Hope this helps!

3 Answers

Hugo Paz
Hugo Paz
15,622 Points

Hi moath,

You are putting the actual values on your function definition,

You should do something like this:

function max(x,y){

  if(y>x){
  return y ;
  }
return x;  
}

max(2,10);

This will check if the y number is larger than x, if so returns y. If the if condition fails (y is not bigger than x), the function returns x.

Adam Stonehouse
Adam Stonehouse
4,645 Points

As Hugo has already stated, you are using static values where you should have variables.

Julia Rix
Julia Rix
3,303 Points

I had something similar and am getting a Parse error. Can anyone help?
function max(x, y) { if (x < y){ return y; }else (x > y) { return x; } } max(4,6);

Hugo Paz
Hugo Paz
15,622 Points

Julia check my answer. The else does not have a condition only the if. Thats why you are getting a parse error.

The if else structure is like this:

if(condition) {
//do something if condition is true
}
else{
//do something if condition is false
}

Regarding our exercise, we check if y is larger than x. If true we return y , if its not true we return x. Now in my solution i omit the else because its not necessary. Either y is larger than x or its not. You could write it like this:

function max(x,y){

  if(y>x){
       return y ;
  }
  else{
       return x;
   }  
}
Julia Rix
Julia Rix
3,303 Points

Oh, I see. Thank you for clarifying. I got it to work, but I didn't really understand why. I just assumed that my code was redundant and the challenge application would not allow for inefficient coding.

Thanks!