thecodezone.
The Code Zone
Short steps, at your pace · Free lessons and practice · Member video walkthroughs
Save your next small win.

Checking your account…

19.10 · Arrays / Practice · 6 min

Keep the greatest candidate

Compare each item against the greatest value seen so far.

Activity 10 of 15 in Arrays

All courses

JavaScript Basics / 19.10

Keep the greatest candidate

Not started

Compare each item against the greatest value seen so far.

More options
Rob compares 3, 7, 12, 5 and 9, keeping 12 as the greatest candidate.
Rob’s comic strip · Arrays

Add array values and calculate an average

Work through 4 focused steps. Read the explanation, type each requested change and check it before moving on. Your own code carries forward.

The mini-lesson opens in a new tab. Your own code carries forward; each step has a focused check and an optional hint.

Start mini-lesson(opens in a new tab)

4 steps · Saved work · Instant feedback

YOUR TURN

Keep the largest value seen so far

Find the largest value in the original nonempty numbers array using only the existing loop, comparison and assignment. Repair the comparison, keep largest initialized from numbers[0], and print Largest: 12. Do not sort, use Math.max, create a helper function or hard-code the answer. The same loop must also work with all-negative values.

Expected output
Largest: 12

Keep the starting inputs. Print these lines in this order, without extra output.

Edit JavaScript, then run it. Check Challenge shows which output checks pass or need a fix. Word wrap is enabled.

Ready to checkRun the checks to see your results here.

Work in VS Code instead

Copy the starter into a file named practice.js in VS Code. If Node.js is installed, open the terminal in that folder and run node practice.js. Compare the output with the task above. Automated challenge checks are available in the browser editor.

Code example
example.jsjavascript · example
const numbers = [3, 7, 12, 5, 9];
let largest = numbers[0];
for (let i = 1; i < numbers.length; i++) {
  if (numbers[i] < largest) {
    largest = numbers[i];
  }
}
console.log("Largest: " + largest);

Need a nudge?

Replace the candidate only when it improves

largest means the greatest value seen so far. Ask whether the current number is greater than that candidate before assigning it.

Start with a value actually in the list

Starting with zero would fail when every value is negative. Keep numbers[0], then scan from index 1. This example assumes a nonempty list.

Replace your editor code?

Your current work will be replaced. Choose Cancel to keep it.

Ready to try it?

Practice in your browser and see your results.

Progress details

Have a question?

Ask the Code Zone community.

Ask a question in The Code Zone (opens in a new tab)

Continue learning

ONE STEP FORWARD

Read one value at a time and keep track of what each index or total means.