 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculating average of an array in JavaScript
Following is the code for calculating average of an array in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .result,    .sample {       font-size: 18px;       font-weight: 500;       color: blueviolet;    }    .sample {       color: red;    } </style> </head> <body> <h1>Calculating average of an array</h1> <div><pre class="sample"></pre></div> <div class="result"></div> <button class="Btn">Check</button> <h3>Click on the above button to see document state</h3> <script>    let resEle = document.querySelector(".result");    let BtnEle = document.querySelector(".Btn");    let sampleEle = document.querySelector(".sample");    let arr = [1, 2, 3, 4, 5, 11, 22];    sampleEle.innerHTML = arr;    BtnEle.addEventListener("click", () => {       let sum = 0;       arr.forEach((item) => (sum += item));       resEle.innerHTML = "The average of the array = " + sum / arr.length;    }); </script> </body> </html>  Output

On clicking the ‘Calculate’ button −

Advertisements
 