Ask coding questions

← Back to all posts
finding the largest number in an array
DamienVapes (1)

I have some code im having trouble with if someone could give me an idea or an answer id be greatly in your debt.

function getLargestNumber(numbers) {


/ Do not modify code below this line /

const largestNumber = getLargestNumber([1, 9, 5]);
console.log(largestNumber, '<-- should be 9');

Answered by LeonDoesCode (431) [earned 5 cycles]
View Answer
LeonDoesCode (431)

In JavaScript, you can use the Math.max.apply() function to do this, like so:

// Will return the largest number
function getLargestNumber(numbers) {
  // Takes in Math and the array of numbers, and returns the largest one
  return Math.max.apply(Math, numbers);

// Or
function getLargestNumber(numbers) {
  return Math.max(...numbers);

This is like calling:

function getLargestNumber() {
  // This function returns the largest number from all the numbers parsed in
  return Math.max(5, 7, 3, 2);

You can also do this with Math.min too.

Hope this is what you were looking for!

theangryepicbanana (1688)

@LeonDoesCode In the future, please do not give direct answers. Instead, try to help them understand how to do it

LeonDoesCode (431)

@theangryepicbanana That is why I also included the second part (after "This is like calling:"). It explains what that function is similar to calling, and how that function works.

However, I see your point, will try to not do this in future. Thanks for the feedback!

DamienVapes (1)

@LeonDoesCode thank you i was over complicating this..i was trying to put in a for loop and everything lol

DamienVapes (1)

@LeonDoesCode how did you post the code the way you did on your earlier like to show my repl completed here

LeonDoesCode (431)

@DamienVapes You can post code like so:

Use these at the beginning and end ```
You can also put a language name on the first one e.g  ```python

I recommend looking at this for more information.

However, if you want to post a Repl, it is recommended that you use the share Repl feature when you post the code (above the title).