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

kevinkrato
kevinkrato
5,452 Points

Function max

No idea how to do this.

script.js
function max (x, y) {
 return x
 if ( x > y ) {
  alert('amazing'); 
 } else {
  alert('sorry, try again'); 
 }
}

1 Answer

Hey there!

You definitely have the basics right. Let's break this down.

Since the program doesn't know how to read numbers from strings by itself, you need to use the 'parseInt()' function for both arguments. Once they are read as numbers, the IF statement can really calculate if x > y.

The RETURN function ends the function, so it shouldn't be in the beginning of the function, like in it is in your code. The RETURN doesn't even let your function get to the IF statement.

The condition of the task says "The function should return the larger of the two numbers" meaning that IF x > y, then it should RETURN the biggest number ( if IF is true, then this number is x). For example: If the statement said "if ( parseInt(y) > parseInt(x) )" and y was the bigger number (aka making the IF statement true), then it should return y.

Here's a visual of the code, in case the explanation is confusing:

function max(x, y) { 
if ( parseInt(x) > parseInt(y)) {
return x;
} else {
return y;
}
}

Good luck!