I was given the following JavaScript program in an interview.
const average = xs => {
let sum = 0;
for (let num in xs) sum += num;
return sum / xs.length;
};
const result = average([2, 4, 6]);
console.log(result); // 4
The interviewer told me to explain how this code works. I thought that the average function simply adds all the numbers in the array and divides the sum by the length of the array. However, this wasn't the correct explanation.
There's a bug in the above code. Nevertheless, it produces the correct answer. Can you find the bug and fix it? In addition, can you explain why the above code produces the correct answer even though it is incorrect?