Average of Numbers

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will dive into the world of JavaScript programming and explore the concept of calculating the average of numbers. Through hands-on exercises, you will learn how to use the Array.prototype.reduce() method and how to write a function to calculate the average of any number of values. By the end of this lab, you will have a solid understanding of how to use JavaScript to perform mathematical operations on arrays of numbers.


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`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28169{{"`Average of Numbers`"}} javascript/data_types -.-> lab-28169{{"`Average of Numbers`"}} javascript/arith_ops -.-> lab-28169{{"`Average of Numbers`"}} javascript/comp_ops -.-> lab-28169{{"`Average of Numbers`"}} javascript/higher_funcs -.-> lab-28169{{"`Average of Numbers`"}} javascript/spread_rest -.-> lab-28169{{"`Average of Numbers`"}} end

How to Calculate the Average of Numbers in JavaScript

To calculate the average of two or more numbers in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the built-in Array.prototype.reduce() method to add each value to an accumulator, initialized with a value of 0.
  3. Divide the resulting sum by the length of the array.

Here's an example code snippet you can use:

const average = (...nums) =>
  nums.reduce((acc, val) => acc + val, 0) / nums.length;

You can call the average function with an array or multiple arguments:

average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2

Summary

Congratulations! You have completed the Average of Numbers lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like