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

Justin Townsend
Justin Townsend
4,720 Points

JavaScript noob

I have tried and failed I got back on the horse and failed again I officially need help!

script.js
function max(lastYear, nextYear){
  return max;
}
max(17, 19);

2 Answers

You need to use the max function from the JavaScript Math object inside your function:

function max(numb1, numb2) {
    return Math.max(numb1, numb2);
}
Eric M
Eric M
11,546 Points

Hi Justin,

This question asks you to return the larger of the two parameters using a conditional statement. You've named your parameters lastYear and nextYear so you'll need to use conditional (if/else) brances to check the numbers against eachother and return the higher one.

As a side note, these are very specific names. If the function were higherYear instead of max these names would make sense, as it is I'd suggest going with something more generic like a and b or firstNumber and secondNumber depending on how descriptive you want to be.

The challenge is looking for something like the below, I've added some comments to describe how we meet the requirement of returning the larger of two numbers.

function max(firstNumber, secondNumber)
{
        // check to see if firstNumber is the higher one
        // if it is we return it
        if (firstNumber > secondNumber)
        {
                return firstNumber
        }
        else
        {
                // if we're in the else branch it means that firstNumber isn't
                // higher than secondNumber, so we can return secondNumber
                // as it must be higher than or at least equal to firstNumber
                return secondNumber
        }
}

Cheers,

Eric