Summing an Array in Javascript

I am having trouble calculating the sum of an array in my code. Instead of adding up all the numbers, it is concatenating them together. For example, if I have grades 90, 95, and 100, the sum shows as 09590100. The first FOR loop successfully pushes the grades into an array, but the second loop where I calculate the total seems to be incorrect.

var numOfGrades = prompt("How many assignments are there?");
var grades = [];
var sum = 0;
var grade = 0;
var avg = 0;

for (var i = 0; i < numOfGrades; i++) {
    grade = prompt("Enter score");
    grades.push(grade);
}

for (var j = 0; j < grades.length; j++) {
    sum += grades[j];
}

avg = (sum / grades.length)

Answer №1

The issue here is that the input is being treated as a string instead of a number - make sure to properly parse it.

for (var j = 0; j < numScores; j++) {
    score = prompt("Enter grade");
    scores.push(parseInt(score));
}

Answer №2

To ensure accurate calculations, it is important to use the parseInt function in Javascript when dealing with grade values treated as strings. By explicitly converting them to integers, you can perform computations successfully. Here is an example:

http://jsfiddle.net/conkman/5Eu7T/

$(document).ready(function(){
var numOfGrades = prompt("How many total assignments?");
var grades = [];
var sum = 0;
var grade = 0;
var avg = 0;

for (var i = 0; i < numOfGrades; i++) {
    grade = prompt("Type in score");
    grades.push(grade);

}

for (var j = 0; j < grades.length; j++) {
    sum += parseInt(grades[j]);
}

avg = (sum / grades.length);
alert(avg);

});

For more information on parseInt, refer to the documentation: http://www.w3schools.com/jsref/jsref_parseint.asp

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that only one button from the collection is activated

One of the features on my website includes 3 blocks with buttons. These buttons trigger a change in the displayed picture when clicked. However, it is crucial to ensure that when a new track is activated, the previous button returns to its original state. ...

The Vue v-for directive encountered an unrecognized property during rendering

Trying to grasp the concept of v-for in Vue JS, especially since I am a newcomer to this framework. Since I am utilizing Django, custom delimiters are necessary. I have a script example that appends a list of objects to a data property: var app = new Vue( ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

Using the `setTimeout` function to swap components

As I work on implementing a setTimeout method, the goal is to trigger an event after a .5 second delay when one of the three buttons (drip, french press, Aeropress) is pressed. This event will replace {{ShowText}} with {{ShowText2}}, which will display &ap ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

JQuery.each is causing an issue due to a potential conflict between JSON and string data types

Hey there, I'm trying to loop through each title in this code but encountering an error in the console that says "cannot use 'in' operator." Everything works fine when I provide an ID from the database. However, when I try to pass in a strin ...

Connecting an admin dashboard to a MERN e-commerce application: A step-by-step guide

In the process of developing an e-commerce platform, I find myself using React.js for the frontend and Node.js/Express.js for the backend. My current challenge lies in creating a seamless dashboard to manage items within the app. One possible solution wo ...

If PHP encounters a division by zero, it will return a zero value

Working on a project involves dividing one array by another, but encountering an issue with division by zero. The warning "Division by zero" appears, yielding the value "INF." Seeking to modify this to return zero instead. As a novice in programming, any h ...

Retrieving a value attribute from the isolated controller of a directive

I have a directive that reads and writes attributes, but I'm having trouble getting it to work as expected. The issue seems to be with the controller inside main-directive.js, which is empty, while the actual action is happening in the isolated direct ...

Retrieve a DOCX file via AJAX response

I am encountering an issue with a Django function that returns a file: ... return FileResponse(open('demo.docx', 'rb')) I am using ajax to fetch it on the client side. Now, I need to download it on the client side. This is the code I a ...

What are some ways to avoid the use of underline and slash symbols in material-ui/pickers?

Is there a way to remove the underline and slash characters that separate day, month, and year in the material ui pickers for version mui version 4? <KeyboardDatePicker margin="normal" id="date-picker-dialog" label="Dat ...

ERROR: Assignment of incompatible types in expanding pointer array

Currently tackling an assignment where I've encountered an error that seems to make no sense. The situation involves a class called "Playlist" containing an array of pointers to "Track" objects. class Playlist{ private: string playlistName; i ...

Asynchronous mismatches occur with React.js useState values

There is an unusual problem I'm encountering where the value passed into useState is different than the variable for useState. This issue occurs consistently on one specific UI component, while others do not experience the same problem. I just want to ...

JavaScript: Implement a function that returns an object with key-value pairs instead of a

Once again, I'm looking at this particular answer. var firstEvents = events.reduce(function(ar, e) { var id = e.getId(); if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) { ar.pus ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

How can I manually include a triangle in BufferGeometry using Three.js?

Recently, I've been exploring the quickest method to change a mesh's vertices using three.js. Through my experimentation, I discovered that modifying parts of mesh.geometry.attributes.position.array and then setting mesh.geometry.attributes.posit ...

In Angular, a variable that is exported from a module may not be accessible within a class function

Within my Angular project, I have a service file where I export a variable to be used in another file (component.ts). Interestingly, when I access the value of this variable outside of the class, everything works as expected. However, if I try to access i ...

When attempting to use a context, the type '...' cannot be assigned to type '...'

In my Next.js project, I am utilizing createContext to implement a dark mode button. The original jsx file for this functionality is called ThemeContext.tsx, and I am currently in the process of converting it to TypeScript. "use client"; import ...

Suspend operation to delay for ajax call within a websocket

Looking for a solution regarding a WebSocket that updates a messaged list when receiving a message. Currently using a fetch request to retrieve data from the server in order to populate the messaged list. However, facing an issue as the code needs to pau ...

This React.Js application hosted on Heroku is optimized for use on Chrome Desktop browsers

Just finished completing a React project that retrieves News Articles and presents them. Recently launched it on Heroku, but I'm encountering an issue where only Chrome on Desktop seems to be able to run it. Both Safari and Firefox are showing the sa ...