TheAlgorithms/JavaScript · error · TypeError
The two lists must be of equal length
Error message
The two lists must be of equal length
What it means
The meanSquaredError function requires element-wise comparison, so predicted and expected arrays must have the same length. This guard fires after the array-type check. A length mismatch would cause the loop to silently skip elements or access undefined values.
Source
Thrown at Maths/MeanSquareError.js:9
// Wikipedia: https://en.wikipedia.org/wiki/Mean_squared_error
const meanSquaredError = (predicted, expected) => {
if (!Array.isArray(predicted) || !Array.isArray(expected)) {
throw new TypeError('Argument must be an Array')
}
if (predicted.length !== expected.length) {
throw new TypeError('The two lists must be of equal length')
}
let err = 0
for (let i = 0; i < expected.length; i++) {
err += (expected[i] - predicted[i]) ** 2
}
return err / expected.length
}
export { meanSquaredError }
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Ensure both arrays have the same number of elements.
- Trim or pad arrays to equal length before calling.
- Check .length equality before invoking.
Example fix
// before
meanSquaredError(pred, actual) // pred.length !== actual.length
// after
if (pred.length !== actual.length) throw new RangeError('arrays must match in length')
meanSquaredError(pred, actual) Defensive patterns
Strategy: validation
Validate before calling
if (predicted.length !== expected.length) {
throw new RangeError('Arrays must have equal length')
}
meanSquaredError(predicted, expected) Type guard
const areEqualLengthArrays = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length
Prevention
- Check .length equality before pairwise comparison operations.
- Trim or pad datasets to matching sizes before calling.
- Audit filtering and train/test splits for asymmetry that changes array lengths.
When it happens
Trigger: Calling meanSquaredError([1,2,3], [1,2]) or any pair of arrays with differing lengths.
Common situations: Truncated datasets, filtering that removed elements from one array but not the other, train/test split mismatches, or predictions generated for a different number of samples than ground truth.
Related errors
- Invalid Input
- Argument must be an Array
- Invalid Input
- Number must be greater than zero.
- Input data must be numbers
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/4c8572e2ab68a6ec.
Report an issue: GitHub.