Calculating average of an array in JavaScript



Following is the code for calculating average of an array in JavaScript −

Example

 Live Demo

<!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 −


Updated on: 2020-07-17T07:50:06+05:30

554 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements