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

Enemuo Felix
Enemuo Felix
1,895 Points

Task challenge 2 of 2

Please Can someone break this down for me ?

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

2 Answers

Steven Sullivan
Steven Sullivan
11,616 Points

Let's break this down line by line:

function max (num1,num2) {

Above you have a function named 'max', with two parameters 'num1, num2'.

The parameters are there so you can pass them into the function's code and do something with them.

In this case, you're comparing them.

  if (num1 > num2) {
    return num1;

Next, you are comparing the two parameters -- which one is greater?

If 'num1' is greater in value than 'num2', the IF statement will return 'num1'

  } else {
    return num2;
  } }

Finally, if the first condition fails -- meaning if 'num1' is NOT greater than 'num2', the ELSE condition will run.

This will return 'num2'

Charles Wanjohi
Charles Wanjohi
9,235 Points

Its a function used to compared two values(numbers ) to determine which is greater than the other.In this case to find which of the two values num1 and num2 is greater than the other.The greater of the two is returned i.e sent back to the caller.The if (num1 > num2) is used to examine if num1 is greater than num2 ...if this condition evaluates to true them num1 is returned, else (meaning false thus num2 greater than num1, num2 is returned.To see it work, call it and pass two arguments i.e

//declare a variable and assign to it the value returned by the max function
var greaterValue=max (10,20);
//output to see the value returned
console.log(greaterValue);

Hope this helps out