What is the best way to calculate the total of all elements in an array?

I am currently learning JavaScript and facing a dilemma about whether to use return, document.write, or both in order to calculate the sum of all values in an array named 'amount'. I have been tasked with creating a function called amountTotal().

The main goal is to return the total sum of all values within the amount array. To achieve this, I need to initialize a variable called total with a starting value of 0. Subsequently, I should implement a for loop that iterates through each value in the amount array.

During each iteration of the loop, I must add the current value of the array element to the existing value of the total variable. When the loop completes, the final step involves returning the calculated total value. The largest value in the array is [34], which will be displayed in a table named Summary.

This snippet shows my progress so far:

<script type="text/javascript">
    function amountTotal() {
        var total = 0;
        for (i = 0; i < 35; i++) {
            document.write("<td>" + i + "</td>")
        }
    }
</script>

Do you think I am heading in the right direction?

Answer №1

Retrieve sum from function.

function calculateTotal(numArray) {
        let sum = 0;
        for (let j = 0; j < numArray.length; ++j) {
             sum += numArray[j]; // add each value in an array to the total sum
        }
        return sum; // returning the final sum of all elements in the array 
}

Answer №2

def sum_list(nums):
    total = 0
    for num in nums:
        # 'num' inside the loop can be any variable name
        total += num
    return total

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

What could be causing the malfunction of AngularJS $scope?

I recently started using AngularJS and I'm trying to create an array and send it to the server using the register function. Below is the Controller code snippet: root.controller('mainController', function($scope) { $scope.lineItems = [ ...

Setting up the page header in Next.js

I integrated some themekit CSS into the head of my Next.js project, but I'm getting a warning in the browser console. What could be causing this issue? Expected server HTML to contain a matching <head> within a <div>. const Layout = ({ ch ...

Distinguishing between a hidden input containing an "empty string" and one that is "null" in Javascript and VB

While attempting to JSON deserialize a collection in VB, I encountered the following issue. Dim items = JsonConvert.DeserializeAnonymousType(Page.Request.Params("Items"), New List(Of ItemDto)) An error occurred during deserialization where the string "va ...

Tips for loading various UI elements on Titanium platform

Can anyone offer guidance on the most efficient method for loading multiple UI objects onto a window using titanium javascript? For instance, if I need to load 50 views into my window as quickly as possible. Currently, I am employing a for loop, but it&a ...

What is the best way to utilize "exports" in package.json for TypeScript and nested submodules?

Looking to leverage the relatively new "exports" functionality in Node.js/package.json for the following setup: "exports": { ".": "./dist/index.js", "./foo": "./dist/path/to/foo.js" } so that ...

The fixed position element appears to be failing to stay fixed in Google Chrome

Something strange is happening with a fixed position element in Chrome. It is still scrolling with the page even though it should be fixed. To better understand the issue, you can view it on the live site In Firefox and even IE, the "Block 1 Block 2 Block ...

Guidelines on maintaining an active getSelection with JavaScript

I need help figuring out how to change the font size of selected text within a div without losing the highlight/selection when I click a button. Can someone assist me in keeping the text highlighted while also resizing it upon clicking the button? ...

Track user engagement across multiple platforms

Looking for solutions to log system-wide user activity in my Electron app. I want to track mouse-clicks and keystrokes to determine if the user is inactive for a certain period of time, triggering a timer reset within the application. I believe I may nee ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

How can you achieve the functionality of jQuery's hide() and show() in JavaScript?

Is there a JavaScript equivalent to my simple hide and show jQuery code? Here is my current code: $(document).ready(function() { $("#myButton").hide(); $("#1").click(function() { $("#myButton").show(); $("#myButton").click(function() { ...

tips on displaying textbox content on a php webpage

I have a piece of code where, when text is entered into a textbox and the add attribute button is clicked, the entered value is displayed on the page twice. One appears in the first row of a table, and the other appears in the first row of a second table. ...

The error message "indexOf of undefined" appears when trying to read a property that does not exist within a new

Help Needed: The following error is happening: Cannot read property 'indexOf' of undefined at new HttpRequest (http.js:653) at HttpClient.request (http.js:1069) at HttpClient.get (http.js:1157) This occurs when I use the get() method from Ht ...

Importing a JavaScript file into an Angular 2 application

Currently, I'm in the process of developing an angular2 application using TypeScript. The Situation: Within my project, there exists a module named plugin-map.ts which is structured as follows: import { Type } from '@angular/core'; impor ...

Inspect every div for an id that corresponds to the values stored in an array

I am in the process of developing a series of tabs based on a preexisting set of categories using the JavaScript code below. Now, I am looking to expand this functionality to target specific IDs within the DIV ID corresponding to values from an array in JS ...

Button to return to top and footer placement

I recently added a "back-to-top" button to my website. Here is the HTML: <div class="scroll-top scroll-is-not-visible"> <a href="#0"><i class="fa fa-angle-up" aria-hidden="true"></i></a> </div> <footer class="site ...

Can flexbox elements be animated as they scroll?

Wondering if it's feasible to animate flex elements upwards when scrolled? Attempting to replicate this effect: https://codepen.io/Sergiop79/pen/bxjGEe I want to apply this to the elements below (styled in flexbox), either the entire "row" or each i ...

Exploring the Benefits of Employing PHP's json_encode Function with Arrays

$cnt = 0; while ($row = $result->fetch_assoc()) { $arre[$cnt]['id'] = $row['idevents']; $arre[$cnt]['title'] = $row['title']; $arre[$cnt]['start'] = "new Date(" . $row['start'] . " ...

Tracking a razor ajax form using pace.js has never been easier with these simple steps

I'm currently exploring the use of pace.js with my Razor ajax form. The form generates a Partial View upon submission. Pace.js, as per its documentation, automatically monitors all ajax requests lasting longer than 500ms without any additional configu ...

Avoid altering the background color through state variables in React

Currently, I am in the process of implementing a dark mode for my app. I have successfully created a state that changes the background color but encountered an issue with changing the background color of the textarea tag using a ternary operator when tryin ...

Managing VueJS components and Observers during the rendering process to ensure smooth functionality in a multi-phase environment

Situation: As part of my development work, I am creating a Vue scroll component that encompasses a variable number of HTML sections. This component dynamically generates vertical page navigation, allowing users to either scroll or jump to specific page lo ...