Standard deviation in plain JavaScript

David James Knight
22 Jul 2019

Standard deviation (“σ”, or sigma, in mathematical notation) is the amount of variation in a data set relative to its mean. A low standard deviation indicates that most of the values are grouped close to the mean, whereas a high standard deviation indicates that the values are spread out over a large range.

In a normal distribution (the classic “bell curve”), 68.27% of values fall within one standard deviation, 95.45% fall within two standard deviations, and 99.73% fall within three standard deviations of the mean, respectively.

Code

This function takes an array of numeric values and returns the standard deviation:

function standardDeviation(arr) {
    return pipe(
        arr => arr.map(x => Math.pow(x - mean(arr), 2)),
        mean,
        Math.sqrt
    )(arr)
}

Note that standardDeviation invokes two other functions: pipe and mean.

The pipe function passes (or “pipes”) an object through a given set of functions in sequence, rather than from the inside out (as in nested functions). This single-line implementation was inspired by Eric Elliot’s writings on functional JavaScript.

const pipe = (...fns) => (obj) => fns.reduce((x, f) => f(x), obj)

The mean function takes an array of numeric values and returns their mean (or average value):

const mean = (arr) => arr.reduce((sum, x) => sum + x, 0) / arr.length

Usage Example

standardDeviation([95, 98, 29, 35, 77, 46, 41, 65, 90, 43])
   
// => 25.05773333723543