Prompt
The following JavaScript function should return the median of an array of numbers, but it has bugs. Fix it. Requirements: return null for an empty array; do not modify the input array; work for negative numbers and decimals; for an even number of elements return the average of the two middle values. Reply with the complete fixed function in a single ```js code block (function name `median`, no exports, nothing else in the block), then at most 3 sentences explaining the bugs. ```js function median(arr) { arr.sort(); const mid = Math.floor(arr.length / 2); if (arr.length % 2 === 0) { return arr[mid] + arr[mid - 1] / 2; } return arr[mid]; } ```
Checklist
- ✓ A js code block is present and defines a function named median
- ✓ median([3,1,2]) === 2
- ✓ median([10,2,1,4]) === 3
- ✓ median([100,20,3]) === 20 (catches default string sort)
- ✓ median([-1,-3]) === -2 and median([1.5,2.5,0.5]) === 1.5
- ✓ median([]) === null
- ✓ The input array is not mutated
Read the full answer (unedited model output, punctuation normalized)
```js
function median(arr) {
if (!Array.isArray(arr) || arr.length === 0) {
return null;
}
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
return (sorted[mid - 1] + sorted[mid]) / 2;
}
return sorted[mid];
}
```
The original sorted the input array in place and used the default lexicographic sort, which misorders negative numbers, decimals, and multi-digit values. The fix sorts a copy with a numeric comparator. It also adds the missing empty-array check and fixes operator precedence so the two middle values are summed before dividing by 2.




























