Calculating variance for an array of numbers in JavaScript

Problem

We need to write a JavaScript function that calculates the variance for an array of numbers. Variance measures how spread out the numbers are from their average (mean).

The variance formula involves two steps:

Mean (M) = (Sum of all numbers) / (Count of numbers)

Variance (V) = (Sum of squared differences from mean) / (Count of numbers)

Understanding Variance

Variance tells us how much the numbers in our dataset differ from the average. A low variance means numbers are close to the mean, while high variance means they're spread out.

Variance Calculation Steps 1. Calculate Mean 2. Find Differences 3. Variance (4+6+7+8+9+10+10)/7 (4-7.7)², (6-7.7)², ... Sum/Count

Implementation

const arr = [4, 6, 7, 8, 9, 10, 10];

const findVariance = (arr = []) => {
    if (!arr.length) {
        return 0;
    }
    
    // Step 1: Calculate the mean
    const sum = arr.reduce((acc, val) => acc + val);
    const count = arr.length;
    const mean = sum / count;
    
    // Step 2: Calculate variance
    let variance = 0;
    arr.forEach(num => {
        variance += Math.pow(num - mean, 2);
    });
    
    // Step 3: Divide by count
    variance /= count;
    return variance;
};

console.log("Array:", arr);
console.log("Mean:", (arr.reduce((a, b) => a + b) / arr.length).toFixed(2));
console.log("Variance:", findVariance(arr));
Array: [4, 6, 7, 8, 9, 10, 10]
Mean: 7.71
Variance: 4.204081632653061

Alternative Implementation

Here's a more concise version using array methods:

const calculateVariance = (numbers) => {
    if (!numbers.length) return 0;
    
    const mean = numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
    const squaredDiffs = numbers.map(num => Math.pow(num - mean, 2));
    
    return squaredDiffs.reduce((sum, diff) => sum + diff, 0) / numbers.length;
};

// Test with different arrays
const testArrays = [
    [1, 2, 3, 4, 5],
    [10, 10, 10, 10],
    [1, 100]
];

testArrays.forEach((arr, index) => {
    console.log(`Array ${index + 1}: [${arr.join(', ')}]`);
    console.log(`Variance: ${calculateVariance(arr).toFixed(3)}<br>`);
});
Array 1: [1, 2, 3, 4, 5]
Variance: 2.000

Array 2: [10, 10, 10, 10]
Variance: 0.000

Array 3: [1, 100]
Variance: 2450.250

Key Points

  • Handle edge cases: Return 0 for empty arrays
  • Mean first: Always calculate the mean before finding variance
  • Square the differences: Use Math.pow() or ** operator
  • Population vs Sample: This calculates population variance (divide by n)

Comparison: Population vs Sample Variance

Type Denominator Use Case
Population Variance n Complete dataset
Sample Variance n - 1 Sample from larger population

Conclusion

Variance calculation involves finding the mean first, then averaging the squared differences from that mean. This implementation handles edge cases and provides an accurate measure of data spread.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements