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

Tony Brackins
Tony Brackins
28,766 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
28,766 Points

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