Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,650 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