Variance and standard deviation in JavaScript
Intermediate · 5 min read
Two classes can both have an average mark of 70. In one, every student scored between 65 and 75. In the other, marks run from 20 to 100. The average hides that difference. Variance and standard deviation measure it: how far, typically, values sit from the mean.
They are used everywhere data is summarized: grading on a curve, quality control in factories, the margin of error in a survey, and the risk figure for an investment. In this tutorial you will compute both, in the two versions you will see in spreadsheets (dividing by n or by n - 1), and you will learn which to use when. Then you will see a popular one-pass shortcut give 0 for a list that clearly varies. You need to know arrays, reduce and the mean.
Deviations, and why we square them
A deviation is how far one value is from the mean. For the list 2, 4, 4, 4, 5, 5, 7, 9, the mean is 5, so the deviations are -3, -1, -1, -1, 0, 0, 2 and 4.
You might want to average the deviations. But they always add up to 0: the values above the mean exactly balance the ones below. So we square each deviation first. Squares are never negative, and big deviations count for more. The squares here are 9, 1, 1, 1, 0, 0, 4 and 16, which add up to 32.
Variance and standard deviation
The variance is the average of those squared deviations. The standard deviation (SD) is the square root of the variance. Taking the root brings the answer back into the same units as the data: if the data is in marks, the SD is in marks too.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
60 Variance and standard deviation: divide by n, or by n - 1
fairCompute the variance and standard deviation of a list both ways — dividing the squared deviations by n and by n - 1 — and say which is which. Then show the one-pass formula mean(x²) - mean(x)² failing on values that are large but close together.
Stuck? Three hints, smallest first
- 1. Sum the squared deviations from the mean, then choose your divisor:
nfor a whole population,n - 1for a sample. - 2. The standard deviation is the square root of the variance, so it is back in the original units.
- 3. The one-pass formula subtracts two nearly equal large numbers, and the digits that survive are the ones that were noise.
Step 1: the mean and the squared deviations
const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
const squaredDeviations = (xs) => {
const m = mean(xs);
return xs.reduce((acc, x) => acc + (x - m) ** 2, 0);
};
const data = [2, 4, 4, 4, 5, 5, 7, 9];
console.log(mean(data)); // 5
console.log(squaredDeviations(data)); // 32
We work out the mean once, store it in m, then add up (x - m) ** 2 for every value. That matches the 32 worked out by hand above.
Step 2: divide by n
If your list is the whole population, every student in the class or every order last month, divide by the number of values, n:
console.log(squaredDeviations(data) / data.length); // 4
console.log(Math.sqrt(4)); // 2
The population variance is 32 / 8 = 4, and the SD is 2. Values in this list typically sit about 2 away from the mean of 5.
Step 3: divide by n - 1
If your list is a sample standing in for something larger, for example 8 customers surveyed out of thousands, divide by n - 1 instead. The reason in one sentence: deviations measured from the sample's own mean come out a little too small on average, and dividing by a slightly smaller number corrects for that.
const variance = (xs, sample = false) =>
squaredDeviations(xs) / (xs.length - (sample ? 1 : 0));
const sd = (xs, sample = false) => Math.sqrt(variance(xs, sample));
console.log(variance(data), sd(data)); // 4 2
console.log(variance(data, true), sd(data, true)); // 4.571428571428571 2.138089935299395
sample = false is a default parameter: if you don't pass a second argument, you get the population version. With true, the divisor is 7, so the sample variance is 32 / 7.
Same eight numbers, two different answers, because they answer two different questions. Neither is wrong. Spreadsheets offer both, and JavaScript's Math has neither, so you choose. Say which one you used.
Step 4: check the units
console.log(sd(data) ** 2); // 4
Squaring the SD gives back the variance. The variance is in "marks squared", which is hard to picture; the SD is in marks, which is why reports usually quote the SD.
Step 5: the one-pass shortcut
There is a well-known algebra shortcut: the variance equals the mean of the squares minus the square of the mean. It doesn't need the mean first, so it looks faster:
const naiveVariance = (xs) => mean(xs.map((x) => x * x)) - mean(xs) ** 2;
console.log(naiveVariance(data)); // 4
console.log(naiveVariance([1, 2, 3])); // 0.666666666666667
console.log(variance([1, 2, 3])); // 0.6666666666666666
On data it agrees. On 1, 2, 3 it is already slightly off in the last digit. Now move the same small spread far from zero:
const offset = [1e9 + 1, 1e9 + 2, 1e9 + 3];
console.log(variance(offset)); // 0.6666666666666666
console.log(naiveVariance(offset)); // 0
These three numbers differ by 1 and 2, so the variance should be 2/3, as the two-pass version says. The shortcut says 0. The squares are about 1e18, far past Number.MAX_SAFE_INTEGER, so they are rounded. Then the formula subtracts two nearly equal huge numbers, and the small difference it needed was lost in the rounding. Every useful digit is gone.
The two-pass version subtracts the mean from each value first. The deviations are small numbers, so nothing is lost. When you can't make two passes, look up Welford's method, which updates the variance one value at a time without this problem.
Step 6: edge cases
console.log(sd([5, 5, 5])); // 0
console.log(variance([5], true)); // NaN
A list where every value is the same has zero spread. A sample of a single value has nothing to measure: the sample divisor is 1 - 1 = 0, and 0 / 0 is NaN.
The full solution
The answer panel has mean, squaredDeviations, variance, sd and the one-pass naiveVariance, then prints the population and sample results for data, both versions on the offset list, and the constant and one-value cases. Press Run to see the output.
const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
const squaredDeviations = (xs) => {
const m = mean(xs);
return xs.reduce((acc, x) => acc + (x - m) ** 2, 0);
};
const variance = (xs, sample = false) =>
squaredDeviations(xs) / (xs.length - (sample ? 1 : 0));
const sd = (xs, sample = false) => Math.sqrt(variance(xs, sample));
// One pass, no stored mean, and no accuracy either.
const naiveVariance = (xs) => mean(xs.map((x) => x * x)) - mean(xs) ** 2;
const data = [2, 4, 4, 4, 5, 5, 7, 9];
const offset = [1e9 + 1, 1e9 + 2, 1e9 + 3]; // spread of 2, sitting a billion out
console.log('mean, sum of squares:', mean(data), squaredDeviations(data));
console.log('population var, sd :', variance(data), sd(data));
console.log('sample var, sd :', variance(data, true), sd(data, true));
console.log('offset two-pass :', variance(offset));
console.log('offset one-pass :', naiveVariance(offset), '<- every digit gone');
console.log('constant list :', sd([5, 5, 5]), 'sample sd of one value:', variance([5], true));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the mean is 5 and the squared deviations sum to 32', [mean(data), squaredDeviations(data)], [5, 32]);
test('dividing by n gives the population variance 4 and sd 2', [variance(data), sd(data)], [4, 2]);
test('dividing by n - 1 gives the sample variance 32/7', variance(data, true), 4.571428571428571);
test('whose square root, the sample sd, is a little larger', [sd(data, true), sd(data, true) > sd(data)], [2.138089935299395, true]);
test('squaring the sd returns the variance, so the units line up', sd(data) ** 2, 4);
test('the two-pass variance of the offset list is 2/3', variance(offset) === 2 / 3, true);
test('the one-pass formula returns a flat 0 for the same list', naiveVariance(offset), 0);
test('a constant list has zero spread, and one sampled value has none to measure', [sd([5, 5, 5]), Number.isNaN(variance([5], true))], [0, true]);
The divisor is a modelling decision, not a detail. Divide by n when the list is the population — every student in the class, every order last month. Divide by n - 1 when it is a sample standing in for something larger, because deviations measured from the sample's own mean are systematically too small, and n - 1 corrects the bias. Here the same eight numbers give 4 or 4.571428571428571 depending on which question is being asked. Spreadsheets default to the sample form; Math gives you neither, so you choose.
mean(x²) - mean(x)² is algebraically identical and numerically hopeless. For values near a billion, mean(x²) is about 1e18 — past Number.MAX_SAFE_INTEGER, where consecutive integers are no longer distinguishable — so subtracting mean(x)² cancels every significant digit and returns 0. The two-pass version subtracts small deviations from a mean first, and gets 2/3 exactly. Where one pass is genuinely required, use Welford's update rather than this.
Common mistakes
- Not saying which divisor you used. n gives 4 and n - 1 gives 4.571428571428571 for the same data. Both are correct for different questions.
- Averaging deviations without squaring. They always add up to 0, so the "spread" comes out as 0.
- Using mean of squares minus square of mean. It gives 0 for values near a billion. Subtract the mean first.
Try it yourself
- Compute the population SD of the marks
[72, 88, 61, 95, 79]. - Add 1000000 to every value in
dataand check thatvariancestill gives 4, then trynaiveVariance. - Write
zScore(x, xs)that returns how many SDsxis from the mean ofxs. What is the z-score of 9 indata?