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

What is wrong with my code?

i'm running into a problem in the JavaScript Basics course with the following task:

Create a new function named max which accepts two numbers as arguments (you can name the arguments, whatever you would like). The function should return the larger of the two numbers. HINT: You'll need to use a conditional statement to test the 2 parameters to see which is the larger of the two.

(task can be found here: https://teamtreehouse.com/library/javascript-basics/creating-reusable-code-with-functions/create-a-max-function )

Here is my code:

function max(value1, value2) {
    value1 = 6
      value2 = 8

  if (value1 > value2) {
        return value1;
  } else if (value2 > value1) {
        return value2;
  }
}

it worked perfectly fine when i tried in the dev tools console but for some reason when i check my work it says: Bummer: The max function doesn't seem to work. It should return the larger of the two numbers.

1 Answer

Steven Parker
Steven Parker
243,266 Points

It's important not to assign values to parameters, it might seem to work when you are testing for those specific values, but it if the function is passed other arguments it will return an incorrect result.

Otherwise, the code will probably pass the challenge even though it still has one small issue. If the two values are the same, the function currently will not return either one! But you can fix it and simplify the code at the same time, just remove the "else if" condition because any time the "if" does not return the first value, you can simply return the second one.

Removing the values made it work. Thanks for the elaborate answer!

Steven Parker
Steven Parker
243,266 Points

I suspected that would be enough, but as I said, a truly correct solution will return a value in all cases.