DocsHub
JavascriptBeginner

Largest Number Finder

Build a tool that finds the largest number from a list of numbers entered by the user.

Largest Number Finder

Problem

Build a tool where the user enters a list of numbers separated by commas and the app finds and displays the largest number. It should also highlight where the largest number appears in the list.

Input: 3, 1, 9, 7, 5
Output: Largest number is 9 (position 3)

Input: 100, 200, 50, 300, 150
Output: Largest number is 300 (position 4)

Input: -5, -1, -3, -2
Output: Largest number is -1 (position 2)

Input: 42
Output: Largest number is 42 (position 1)

Input: abc, 1, 2
Output: Please enter valid numbers only

Logic

  1. Select the input field, button, and result display
  2. Listen for a click on the button and Enter key on the input
  3. Read the input value and split by comma
  4. Trim each item and filter out empty strings
  5. Validate — check if all items are valid numbers
  6. Convert strings to numbers
  7. Find the largest using Math.max()
  8. Find the position of the largest number in the original array
  9. Display the result and highlight the number in the list

Flow

no yes User clicks Find Read input value Split by comma Trim and filter empty strings All valid numbers? Show error message Convert to numbers Find max with Math.max Find position of max Display result and highlight

HTML Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Largest Number Finder</title>
    <style>
      body {
        font-family: sans-serif;
        max-width: 500px;
        margin: 60px auto;
        padding: 0 20px;
      }

      /* input and button sit side by side */
      .input-row {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
      }

      input[type="text"] {
        flex: 1;
        padding: 12px;
        font-size: 1rem;
        border: 2px solid #ccc;
        border-radius: 8px;
        outline: none;
      }

      input[type="text"]:focus {
        border-color: #555;
      }

      button {
        padding: 12px 20px;
        font-size: 1rem;
        font-weight: 600;
        background: #111;
        color: #fff;
        border: none;
        border-radius: 8px;
        cursor: pointer;
      }

      button:hover {
        opacity: 0.85;
      }

      /* result box */
      #result {
        padding: 16px;
        border-radius: 8px;
        background: #f5f5f5;
        font-size: 1rem;
        color: #333;
        min-height: 50px;
        display: none;
      }

      #result.error {
        background: #fff0f0;
        color: #c0392b;
      }

      #result.success {
        background: #e6f9ee;
        color: #1a7a3f;
      }

      /* the number list shown below the result */
      #number-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 16px;
      }

      /* each number pill */
      .number-pill {
        padding: 6px 14px;
        border-radius: 20px;
        background: #e0e0e0;
        font-size: 0.95rem;
        font-weight: 500;
        color: #333;
      }

      /* the largest number gets highlighted */
      .number-pill.largest {
        background: #1a7a3f;
        color: #fff;
      }
    </style>
  </head>
  <body>
    <h1>Largest Number Finder</h1>

    <div class="input-row">
      <!-- user types comma-separated numbers here -->
      <input
        type="text"
        id="number-input"
        placeholder="e.g. 3, 1, 9, 7, 5"
      />
      <!-- click to find largest -->
      <button id="find-btn">Find</button>
    </div>

    <!-- result and number pills shown here -->
    <div id="result"></div>
    <div id="number-list"></div>

    <script src="script.js"></script>
  </body>
</html>

Solution

// Step 1 — select elements
const numberInput = document.querySelector("#number-input");
const findBtn = document.querySelector("#find-btn");
const result = document.querySelector("#result");
const numberList = document.querySelector("#number-list");

// Step 2 — listen for button click
findBtn.addEventListener("click", findLargest);

// also trigger on Enter key press inside the input
numberInput.addEventListener("keydown", (e) => {
  if (e.key === "Enter") findLargest();
});

function findLargest() {
  const value = numberInput.value.trim();

  // Step 3 — handle empty input
  if (!value) {
    showError("Please enter at least one number.");
    return;
  }

  // Step 4 — split input by comma and clean each item
  // split(",") breaks "3, 1, 9" into ["3", " 1", " 9"]
  // .map(item => item.trim()) removes spaces → ["3", "1", "9"]
  // .filter(item => item !== "") removes any empty strings from trailing commas
  const parts = value
    .split(",")
    .map((item) => item.trim())
    .filter((item) => item !== "");

  // Step 5 — validate that every item is a real number
  // Number("abc") returns NaN — isNaN catches this
  const hasInvalidItem = parts.some((item) => isNaN(Number(item)));

  if (hasInvalidItem) {
    showError("Please enter valid numbers only.");
    return;
  }

  // Step 6 — convert all strings to actual numbers
  const numbers = parts.map(Number);

  // Step 7 — find the largest number
  // Math.max(...numbers) spreads the array as individual arguments
  const largest = Math.max(...numbers);

  // Step 8 — find the 1-based position of the largest number
  // indexOf finds the first occurrence — position is 0-based so add 1
  const position = numbers.indexOf(largest) + 1;

  // Step 9 — display the result
  showSuccess(`Largest number is ${largest} (position ${position})`);

  // Step 10 — render number pills and highlight the largest
  renderPills(numbers, largest);
}

// helper — shows a success message
function showSuccess(message) {
  result.style.display = "block";
  result.className = "success";
  result.textContent = message;
  numberList.innerHTML = "";
}

// helper — shows an error message
function showError(message) {
  result.style.display = "block";
  result.className = "error";
  result.textContent = message;
  numberList.innerHTML = "";
}

// helper — renders each number as a pill
// the largest number gets the "largest" class (green highlight)
function renderPills(numbers, largest) {
  numberList.innerHTML = numbers
    .map((num) => {
      const isLargest = num === largest;
      return `<span class="number-pill ${isLargest ? "largest" : ""}">${num}</span>`;
    })
    .join("");
}

Code Execution

Trace through input "3, 1, 9, 7, 5":

StepCodeResult
Split"3, 1, 9, 7, 5".split(",")["3", " 1", " 9", " 7", " 5"]
Trim each.map(item => item.trim())["3", "1", "9", "7", "5"]
Filter empty.filter(item => item !== "")["3", "1", "9", "7", "5"]
ValidateisNaN(Number("3"))false — all valid
Convert.map(Number)[3, 1, 9, 7, 5]
Find maxMath.max(3, 1, 9, 7, 5)9
Find positionindexOf(9) + 13
OutputLargest number is 9 (position 3)

Trace through input "abc, 1, 2":

StepCodeResult
Split and trim["abc", "1", "2"]
ValidateisNaN(Number("abc"))true — invalid
OutputPlease enter valid numbers only

Trace through input "-5, -1, -3":

StepCodeResult
Convert.map(Number)[-5, -1, -3]
Find maxMath.max(-5, -1, -3)-1
Find positionindexOf(-1) + 12
OutputLargest number is -1 (position 2)

Output

Input: 3, 1, 9, 7, 5       → Largest number is 9 (position 3)
Input: 100, 200, 50, 300   → Largest number is 300 (position 4)
Input: -5, -1, -3, -2      → Largest number is -1 (position 2)
Input: abc, 1, 2           → Please enter valid numbers only
Input: (empty)             → Please enter at least one number

On this page