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

Kristen Hickman
Kristen Hickman
2,581 Points

I'm having a hard time getting started with this one...

I'm struggling trying to understand how I can set this up....

script.js
function max ( 1, 2) {
  var maxNumber = 
}

3 Answers

Your arguments can be named anything but a number. In your code, they must be variables. Those variables will hold the value of the numbers that are given when the function is called. They can be named whatever, but name them best so that you understand what it is when you do the math. The could be number1 and number2 if you wanted to.

In the lesson, you just have to return whichever of the two variables you are accepting is the largest. Remember IF statements and > and < comparison? Start with that and see if that meets the requirements for the task.

Sometimes it helps with just writing out what you want it to do in your code. Good luck!

Kristen Hickman
Kristen Hickman
2,581 Points

Thank you! I think that's where I was confused... Instead of creating a variable, I was just putting numbers.

You need to write this: Function max ( first, second ) { (If first > second) { return first // Alert ( first ); } Else { return second // Alert ( second ); } } // Add the numbers max ( 2, 5 ); // Second number is greater so return 5 or bring up an alert if the comment code ( // ) is removed.

Hope, this works for you. Best of luck. Cheers!

Thomas Nilsen
Thomas Nilsen
14,957 Points
//Steps for creating a function:

//function <name of function> (we chose to call this max)
//The arguments (a, b) can be called whatever you want
//Use the argument names inside the function when you perform the differnt checks.

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


    //You could write this instead of the if/else
    //Explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

    //return (a > b) ? a : b;
}


//Actually CALLING the function

//Since the function returns something we can store the result in an variable
//When we actually call the function we pass in the actual numbers we'd like to check
//When we say max(1, 2) - Our function will map 1 = a and 2 = b.
var result = max(1, 2);


//prints 2
console.log(result);