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

Ashley Davison
Ashley Davison
1,883 Points

How do you make a function that accepts 2 answers as arguments, selects the larger of the two numbers, and then returns?

I can't get past this code challenge. I just don't understand what it's asking me to do. I understood the JavaScript functions in a simpler format, but I just can't seem to wrap my head around piecing this challenge together. Any help would be greatly appreciated!

script.js
function max ( , ) {
  var 
  return ; 
}

1 Answer

Tony Nguyen
Tony Nguyen
24,934 Points

Hey how's it going Ashley, let's think about this logically.

So we need a function that accepts two arguments, let's call them "a" and "b".

How would we make it so that it would give us the bigger number from the two? We can try to find out of "a" is bigger than "b" and then return "a" if it is, but if not, just return us "b" because that's obviously the bigger one if the first condition wasn't true.

function max(a , b) {
 if (a > b) {
  return a;
 } else {
  return b;
  }
}
Ashley Davison
Ashley Davison
1,883 Points

Think you could help me on the second part of the challenge as well?: Call the function and display the results in an alert dialog. You can pass the results of a function directly to the alert() method.

I have:

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

It makes sense to me to put the alert after the final curly brace, but when I do that it gives me an alert that the first task is no longer passing. If I put it where the alert currently is, it tells me I'm not using the alert function. What am I missing here?

Tony Nguyen
Tony Nguyen
24,934 Points

The second challenge is simply asking you to alert the function that you had just made.

For example:

alert(max(5, 2));
Tony Nguyen
Tony Nguyen
24,934 Points

Also, you need to make sure to call the alert outside of the function, calling it inside the function is called recursion, however you won't be learning that just yet. :)