Calculate Variance and Standard Deviation in Javascript

Last updated on November 15, 2021 The Plumber Loading... Post a comment

This short article shows you how to calculate the variance and standard deviation of a given array of numbers. You will see the code in vanilla Javascript and TypeScript.

Javascript

// Calculate the average of all the numbers
const calculateMean = (values) => {
    const mean = (values.reduce((sum, current) => sum + current)) / values.length;
    return mean;
};

// Calculate variance
const calculateVariance = (values) => {
    const average = calculateMean(values);
    const squareDiffs = values.map((value) => {
        const diff = value - average;
        return diff * diff;
    });
    const variance = calculateMean(squareDiffs);
    return variance;
};

// Calculate stand deviation
const calculateSD = (variance) => {
    return Math.sqrt(variance);
};

// Test our function
const input = [1, 4, 7, 9, 32, 48, 54, 66, 84, 91, 100, 121];
const variance = calculateVariance(input);
const sd = calculateSD(variance);
console.log(`Variance: ${variance}`);
console.log(`Standard Deviation: ${sd}`);

Output:

Variance: 1583.409722222222
Standard Deviation: 39.79208114967376

TypeScript

If you use TypeScript as your development language then you might want to examine this piece of code:

// Calculate the average of all the numbers
const calculateMean = (values: number[]): number => {
  const mean = (values.reduce((sum, current) => sum + current)) / values.length;
  return mean;
}

// Calculate variance
const calculateVariance= (values: number[]): number => {
  const average = calculateMean(values);
  const squareDiffs = values.map((value: number): number => {
    const diff = value - average;
    return diff * diff;
  })

  const variance = calculateMean(squareDiffs);
  return variance;
}

// Calculate stand deviation
const calculateSD = (variance: number): number => {
  return  Math.sqrt(variance);
}

// Test it
const input = [1, 4, 7, 9, 32, 48, 54, 66, 84, 91, 100, 121];

const variance = calculateVariance(input);
const sd = calculateSD(variance);

console.log(`Variance: ${variance}`);
console.log(`Standard Deviation: ${sd}`);

It will produce the same results as the snippet of Javascript code above.

Further reading:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like