Home > Web Front-end > JS Tutorial > body text

Find the maximum number in an array - JavaScript

Susan Sarandon
Release: 2024-10-08 20:23:29
Original
391 people have browsed it

Find the maximum number in an array - JavaScript

Find the maximum number from an array of positive integers using JavaScript

Solution

//findMaxNumber.js
function findMaxNumber(numbers) {
//Initializes result to track the maximum number, starting at 0.
  let result = 0;

  //Stores the length of the numbers array for use in the loop.
  const numbersLength = numbers.length;

  //Check if the array is not empty before processing it.
  if (numbersLength > 0) {

    //Loops through each number in the array.
    for (let i = 0; i < numbersLength; i++) {

      //Compare each number to the result to check if it's larger.
      if (numbers[i] > result) {

        //Updates result with the current number if it's the largest
        result = numbers[i];
      }
    }
    console.log(result);
    return result;
  }

  return result;
}

findMaxNumber([5, 33, 47, 103]);
Copy after login

Result

> 103
Copy after login

The above is the detailed content of Find the maximum number in an array - JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template