The Largest Number in an Array

JavaScript

Function to find the largest number in an array:

Create a function in JavaScript to find the largest number in an array by iterating through the array and keeping track of the maximum value found. Here's how you can implement it:

js Copy Code
function findLargestNumber(arr) {
  if (arr.length === 0) {
    return undefined; // Return undefined for an empty array
  }

  let largest = arr[0]; // Assume the first element is the largest

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > largest) {
      largest = arr[i]; // Update the largest value if a larger value is found
    }
  }

  return largest;
}

// Example usage:
const numbers = [5, 2, 9, 15, 1, 7];
const largestNumber = findLargestNumber(numbers);
console.log("The largest number is:", largestNumber);
Output:
The largest number is: 15

Explanation:

1. We first check if the array is empty, in which case we return 'undefined'.

2. We initialize the variable 'largest' with the first element of the array.

3. We then iterate through the array starting from the second element.

4. In each iteration, we compare the current element with the 'largest' variable and update 'largest' if the current element is greater.

5. Finally, we return the 'largest' variable which holds the largest number found in the array.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.