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

Michael Gardiner
Michael Gardiner
4,282 Points

What am i missing?

The challenge asks me to: 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.

script.js
function max(x, y) {
  var bigger = x-y;
  if (parseInt(bigger) > 0) {
    return parseInt(bigger);
  }
}
max(20, 10);

3 Answers

Niclas Valentiner
Niclas Valentiner
8,947 Points

Any of the 2 above answers would work well although I suggest using Mauro Introzzi's if you don't understand the ternary operator.

Joseph Neenan's example is the simplest though.

A quick reference for how the ternary operator works: [expression] ? [return if expression is true] : [return if expression is false]

Joseph Neenan
Joseph Neenan
3,363 Points

Here's how I passed this task:

    function max(x, y){

      return (x > y ? x:y)

    };

Hope this helps =]

Mauro Introzzi
Mauro Introzzi
11,080 Points

Hi Michael. It's more simple:

function max(num1, num2) {
  if (num1 > num2) {
    return num1; 
  }
  else{
    return num2;
  }
}

ciao!