How to loop through an array in javascript and calculate the total?

Hey there! I'm a bit confused and couldn't find the solution anywhere. Are you able to take a look at my code and point out what's wrong with it? I promise, I'm not trying to get you to do my homework!

Question: Loop through an array For this challenge, write a function that accepts an array as input. The function should loop through each element of the array and return the sum of all values. Mastering the ability to iterate over arrays is crucial in coding so make sure to practice this often. Try to complete this task within 2 minutes before moving on to the next challenge. (Test cases: [0] should return 0, [1,2,5] should return 8, [-5,2,5,12]should return 14)

My code:

function iterArr(arr) {
  //your code here 
  var s = new Array();
  a[0]=0;
  a[1]=[1+2+5];
  a[2]=[-5+2+5+12];

  for (var i =0;i<s.length;i++){
    sum = sum +s;
  }
  return sum; 
}

Answer №1

It seems like your array (s) is not initialized with any values, causing the for loop to never run. Additionally, the variable sum is also uninitialized, leading to it returning undefined. To fix this issue, update the for loop to iterate over arr.length and initialize the variable sum. Once you make these adjustments, your code will be very close to completion.

function calculateSum(arr) {
  //your logic here 
  var sum = 0;

  for (var i =0;i<arr.length;i++){
    sum += arr[i];
  }
  return sum; 
}

console.log(calculateSum([5,10,15]));

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

Issue with selecting rows in DataTable on subsequent pages

I am currently working on an ASP.NET MVC web application and encountering some issues with a jQuery dataTable. The table is being populated correctly with data from a ViewBag, so that part is working fine. <div> <table id="invoiceTable"> ...

How to transfer data from local storage to PHP using Ajax

Is there a way to pass values from JavaScript to PHP that are stored in local storage? JavaScript let cartItems = localStorage.getItem("productsInCart"); var jsonString = JSON.stringify(cartItems); $.ajax({ url:"read.php", method: "post", da ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

What is the most efficient way to delete every other index from an Array list until all elements have been removed?

I have been struggling with this issue for quite some time and I would really appreciate some help. I need to remove all the numbers at even indices from the given input. Input = 1,2,3,4,5,6,7,8,9,10 Output should be: 1) 1,3,5,7,9 2) 1,5,7,9 3) 1,7,9 ...

How do I assign a variable to a session in Express.js?

I am currently working on a login form that prompts users to enter their username, password, and company name. The company name corresponds to the database name, so I need to store this information in the session during the login post request. In my opini ...

Exploring the performance capabilities of web applications using Visual Studio and JavaScript

Currently, I am in the process of conducting a web performance test on a webpage, and my goal is to calculate the time elapsed from when I click on a button to when the desired next page is fully rendered. The challenge lies in the fact that there is a si ...

Invoke a method from a related component within the same hierarchy

Imagine this scenario: You're working on a reusable item carousel. The slide track component and the slide navigation component need to be independent and in a sibling relationship so you can position the buttons wherever you want. But how do you trig ...

Tips for converting a callback's return value into a string

I'm working with a TypeScript code that involves an array called data. This array is structured like [ {employee:"Jason",employeeRole:"teacher",id:10,gender:"male"}, {employee:"Mark",employeeRole:"student",id:10,gender:"male"}, ... ]. My task is t ...

Starting up a React application with the constructor

I am trying to understand the logic behind having to instantiate a new AppInitializer in order to run it. Why is it necessary to use new AppInitializer().run(); instead of just AppInitializer.run();? class AppInitializer { run() { render( &l ...

Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post. <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ...

Is there a way to retrieve a specific Java array element using a variable as a reference?

I have created several arrays for future use: int[] A1a=new int[20]; int[] B1a=new int[30]; int[] A1b=new int[20]; int[] B1b=new int[30]; int[] A2a=new int[20]; int[] B2a=new int[30]; int[] C2a=new int[40]; int[] A2b=new int[20]; int[] B2b=new int[30]; int ...

Incorrect scroll position being updated

My current project involves dynamically adding a class to the DOM based on scroll position. If the scroll position is 150 or above, a class is added, and if it's less than 150, the class is removed. Everything works fine when scrolling down, but when ...

Display Checkbox Selections in a Popup Message Box

I've run into a problem while working on an assignment. My goal is to show the checkbox values for toppings in the alert box popup upon submission. However, only the text box and radio values are displaying, while the checkbox returns as blank. Any ...

Inserting a Div Element into a List Using a User-Entered Variable (jQuery)

For a school project, I am currently working on a task involving multiple "Add Task" buttons with prompts that appear when clicked. The goal is to have the entered item added to the bottom of the corresponding list. I have experimented with options like a ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

Is there a way to verify if the meteor.call function was executed successfully?

In my meteor/react application, I am working with two components. I need to pass a method from one component to the other: saveNewUsername(newUsername) { Meteor.call('setNewUsername', newUsername, (error) => { if(error) { ...

Tips on how to retrieve the value of a number-type input within a custom attribute directive

I have successfully implemented this code in IE 11, but now we are looking to transition away from IE11 and address some of the issues that have arisen. <input type="number" evaluate-input="model.personalNumber" ng-model="model ...

Modify and improve promise and promise.all using the async/await feature of ES2017

I have successfully implemented a photo upload handler, but I am now exploring how to integrate async await into my code. Below is the working version of my code using promises: onChangePhotos = (e) => { e.preventDefault() let files = e.target ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...