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

Needed help with the max function challenge. I just had a little trouble understanding my instructions.

I would like if someone could show me an example. Just to get the right idea.

script.js
var max = 13

function max(12, 15){
if (max > 12){
  alert('max');
} else {
alert('too bad');
}
  return max
}
Antonio De Rose
Antonio De Rose
20,885 Points

first, calling function should, have 2 parameters, as the function is accepting 2 parameters. function max, should have variables like a, b, and not numbers return has to be in both the parts of the if and else, cause, always a nor b is going to be large

function max(one, two){
  if (one > two){
    alert(one);
    return one;
  }else{
    alert(two);
    return two;
  }
}

var max_num = max(12, 13);

1 Answer

andren
andren
28,558 Points

When you create a function the thing you specify in the parentheses are what are called parameters. Parameters are essentially variables which are assigned a value when the method is called. You can't use pure values like numbers or strings as parameters since the entire point of them is to enable you to pass data in to the function when you call it.

Here is an example of the solution with some comments added to clarify some things:

function max(a, b) { // a and b are parameters which will be set to a value when the function is called 
  if (a > b) { // Check to see which number is largest
    return a // Return a if it is largest
  } else {
    return b // if a is not largest then b has to be the largest one, so return it
  }
}

If the above function where called like this:

max(5, 2) // 5 is the first argument, 2 is the second

Then the a parameter within the function would equal 5 and b would equal 2. Simply due to the position of the parameters relative to the position of the values passed in. The values placed within parentheses when calling a function are called arguments. The arguments provided gets mapped to the functions parameters when the function is called.

If you have any further questions about functions, parameters and arguments or felt a part of my explanation was unclear then feel free to ask any question you want. I'll do my best to answer.

Sweet answer :+1: