Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Calculate the average of array elements in Javascript

I got this Javascript exercise. The average should be 11.2, but my program returned 5420502.4.


Define an empty array. Also create two functions:

addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.

printInfo() outputs the amount of elements in the array to the console, then the average of their values.

The HTML document has two buttons for calling the functions.


var arr = [];

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(num);
}

function printInfo() {
    var len = arr.length;
    console.log("The array has " + len + " elements.");
    
    var total = 0;
    for (var i = 0; i < len; i++) {
        total += arr[i]; // replace arr[i] with +arr[i]
    }
    var avg = total / len;
  // additionally render result to UI
  document.getElementById("info").innerText = avg;
    return console.log("The average of the values is " + avg);
}
.outerStyle { border: 2px solid black; width: 45%; }
.inpStyle { padding: 10px; margin: 10px; }
button { margin: 10px; }
<div id="outer" class="outerStyle">
  <div class="inpStyle">
    <label for="num">Enter number: </label>
    <input id="num" type="number" />
  </div>
  <button id="addBtn" onclick="addNumber()">Add</button>
  <button id="printInfo" onClick="printInfo()">Print Info</button>
  <hr/>
  <div id="info" />
</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The value from your input is a string. So, it will concatenate in to total. If your input value was 1 and you added it to the array twice, your array would consist of 2 strings, "1" and "1". Then, you're adding this, which makes "11" because you're adding strings together.

You'll want to use something like parseInt to convert the string to a number first.

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(parseInt(num));
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!