Calculating Standard Deviation in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of standard deviation in statistics and its implementation in JavaScript. We will learn how to calculate the standard deviation of an array of numbers using the Array.prototype.reduce() method and understand the difference between sample and population standard deviation. By the end of this lab, you will have a better understanding of statistical analysis and how to apply it in JavaScript programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28624{{"`Calculating Standard Deviation in JavaScript`"}} javascript/data_types -.-> lab-28624{{"`Calculating Standard Deviation in JavaScript`"}} javascript/arith_ops -.-> lab-28624{{"`Calculating Standard Deviation in JavaScript`"}} javascript/comp_ops -.-> lab-28624{{"`Calculating Standard Deviation in JavaScript`"}} javascript/higher_funcs -.-> lab-28624{{"`Calculating Standard Deviation in JavaScript`"}} end

Standard Deviation

To calculate the standard deviation of an array of numbers in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the function standardDeviation(arr, usePopulation = false) provided below.
  3. Pass an array of numbers as the first argument to the function.
  4. Omit the second argument, usePopulation, to get the sample standard deviation. Set it to true to get the population standard deviation.
const standardDeviation = (arr, usePopulation = false) => {
  const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
  return Math.sqrt(
    arr
      .reduce((acc, val) => acc.concat((val - mean) ** 2), [])
      .reduce((acc, val) => acc + val, 0) /
      (arr.length - (usePopulation ? 0 : 1))
  );
};

Example usage:

standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)

Summary

Congratulations! You have completed the Standard Deviation lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like