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

Tony Brackins
Tony Brackins
26,686 Points

JS MaxNumber function Help

Hey Guys, can you please help me with this issue?

I'm creating a function that allows me to return the highest number in an array. Can you please take a look?

https://jsbin.com/vadosas/edit?js,console

1 Answer

Karolin Rafalski
Karolin Rafalski
11,368 Points

Here is one answer:

var numbers2 = [1, 4, 3, 7, 17, 267,267, 387,12, 12, 35];
var result;

function max(arr) {
  for (var i = 0; i < arr.length-1; i++) {
    if (arr[i] > arr[i + 1]){
        result = arr[i];
    } else if (arr[i] > arr[i + 1]) {
      result = arr[i];

    } else {
        /*do nothing, and counter will go up (this will deal with equal values) */
    }
    }

    console.log("i is : " + i);
    console.log("Result is " + result);

  return result;
}
console.log(max(numbers2));

alternatively there is a function Math.max that you could use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

Tony Brackins
Tony Brackins
26,686 Points

Thanks, sooooo much, I understand now. I'm still in the process of learning so didn't want to use the math function.