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

Orco The Great
Orco The Great
2,081 Points

Javascript Stage 5 Task 1

this works when i run in my workspace but not when evaluated in the Task page.

Can anyone help me work out why it says the max() doesnt work?

script.js
function max(n1,n2){

  var n1=parseInt(prompt("Enter a number"));
  var n2=parseInt(prompt("Enter another number"));

  var nmax;
  if(n1>n2){
    nmax=n1;

  } else {
    nmax=n2;
  }

  return(nmax);

}

var response=alert(max(2,8)+" is the larger of the two numbers you entered");

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Orco,

I'm not sure where you got all the prompt code from but for this challenge it's not required as we're only creating a function that conducts an A/B test which is what this type of comparison is known as.

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

Personally I don't believe in redundant else statements such as the one above so I void them wherever they aren't needed.

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

  return b;
}

Happy coding!

Orco The Great
Orco The Great
2,081 Points

Thanks Chris. I understand now. Cheers