โ† Git, Tools & AI
#7 most askedVery commonEasyTesting

Find and fix the bug, then test it

New to Testing? Learn it from scratch first
Unit Testing & Test-Driven Development โ†’
๐Ÿข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.
I was asked this

This function is supposed to return the average of a list, but it crashes or misbehaves on some inputs. Write a corrected average(nums) that returns 0 for an empty list, and handles negatives and decimals.

function average(nums) {
  let total = 0;
  for (let i = 1; i <= nums.length; i++) total += nums[i];
  return total / nums.length;
}

๐Ÿงช Practice

Write your solution, then press Run tests. Explain your approach out loud as you go.

JavaScript
function average(nums) {
  // your code here
}

Output appears here. Press Run or Ctrl/โŒ˜ + Enter.

Try it first. Struggling for a few minutes is how it sticks.