# Calculating variance for an array of numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## Problem

We are required to write a JavaScript function that takes in an array of numbers sorted in increasing order.

Our function should calculate the variance for the array of numbers. Variance of a set of numbers is calculated on the basis of their mean.

$Mean (M) = ( \sum_{i=0}^{n-1} arr[i])$ / n

And variance (V) = $(\sum_{i=0}^{n-1} (arr[i] - M)^2)$ / n

## Example

Following is the code −

Live Demo

const arr = [4, 6, 7, 8, 9, 10, 10];
const findVariance = (arr = []) => {
if(!arr.length){
return 0;
};
const sum = arr.reduce((acc, val) => acc + val);
const { length: num } = arr;
const median = sum / num;
let variance = 0;
arr.forEach(num => {
variance += ((num - median) * (num - median));
});
variance /= num;
return variance;
};
console.log(findVariance(arr))

## Output

4.204081632653061