Cost calculation algorithm in javascript

Currently struggling with creating a code that my friend and I were assigned. The task is to calculate and return the average of all values in an array called customerBalance. This array represents the amount customers owe my fictional business, with each item in the array representing a customer's balance. The goal is to use a for loop to process the array, calculate the average by dividing the sum by the length of the customerBalance array, and then return this average.

This is what I have attempted so far:

function average() {
    customerBalance
    for(i=0,i++)
      sum(customerBalance)
    total=sum/5

return average;

I am aware that this code is completely wrong. I am unsure how to properly work with arrays and would appreciate any guidance on how to approach this problem. Your help is greatly appreciated!

Thank you and have a wonderful day

Answer №1

function calculateAverage(customerBalance) {
    if (customerBalance.length == 0) { // Avoiding division by zero later on
        return 0;
    }
    var total = 0;
    for (var i = 0; i < customerBalance.length; i++) {
        total += customerBalance[i];
    }
    var result = total/customerBalance.length;
    return result;
}

You are facing several issues:

  1. The parameter should be placed inside the parentheses after the function name, not on the next line.
  2. Your for() loop syntax is incorrect. Separate the initialization, repetition test, and increment with semicolons.
  3. There is no sum() function in JavaScript. If such a function existed, you would need to assign the result to a variable.
  4. When calculating the average, you are storing it in total, but then returning average, which actually holds the function itself rather than the calculated average.

Additional suggestions:

  1. Avoid hard-coding the array size; use array.length instead.
  2. Always include braces around the body of for, if, while, etc., even for single-line statements.
  3. Declare local variables using var.

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

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

Constant pointer to an array

Take a look at this example: void IncreaseValue(int *num) { num++; } int main() { int num[] = {1,2,3,4,5}; // num++ // This is not legal because it's a constant pointer IncreaseValue(num); // This is allowed } I'm curious ho ...

Using the syntax ['] to access dynamic properties in Typescript

class Bar{ dynamicProperty: string; } I am curious about the behavior when accessing dynamic object properties. I came across an interesting approach in one of the answers provided here: let barObj: Bar = someObj['dynamicProperty']; However, ...

Ways to update the value of an input element programmatically

Currently, I am in the process of developing a Todo application. While I have successfully implemented the functionality to create todos and display them, I am facing an issue where each todo item needs to have an input tag that allows for changing the nam ...

Determine the differences between two arrays using AS3

I have two arrays. The first array contains predefined elements, while the second array collects elements at run-time. I need to compare these two arrays and determine if they are identical. Here are some examples: var array1 = new Array("b1", "b2", "b3 ...

Failure to display alert message upon completion of AJAX request

I am attempting to use AJAX to send data to the database without refreshing the page when a user favorites a message. Even though the data is successfully sent to the DB, the page still reloads and the alert message I want to display is not showing up. Th ...

Steps for checking if the specified row has been accurately filled out in a loop

Here is an example of how my JSON data is structured: { "main_object": { "id": "5", "getExerciseTitle": "TestFor", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFor", "language": "nl_NL", "exercises": [ { ...

Colorful Background Switcher

I am looking to create a set of buttons representing the colors ROYGBV. I want to use JavaScript to apply a function that will change the background color when each button is clicked. The current code I have seems too lengthy. Can someone assist me with ...

Retrieve the specified columns as per user-defined filters

Being completely new to JavaScript, I have been assigned the task at hand. The technology stack includes node.js, express, mongodb, and mongoose. Imagine that the database/collection(s) consist of 1000 rows and each row has 50 columns. Some columns may h ...

Adding more rows to the array and then inserting them into the database

Seeking some clarity and appreciation in advance for any assistance! I've organized an array of information within a table that I can edit and then sync with my database once updated. <input type='button' value='add row' id=&a ...

How can the @blur event be added to the vue-bootstrap-typeahead in Nuxt/Vue application?

I am facing an issue where I want to trigger a function upon leaving an input field. The input in question is set up using vue-bootstrap-typeahead. Upon inspecting the DOM, I found that the structure of the input element looks like this: <div id="m ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Discovering the largest value within an array comprising multiple lists using Scala

Having an array of lists works like this: val myArray = Array( List(1, "120", "a"), List(3, "97", "v"), List(7, "110", "d") ) The goal is to identify the array element with the highest second element. I can achieve this by running: myArray.maxBy(_(1).to ...

Consistently navigating back to the Home Page through AJAX

Can anyone assist me in resolving my issue? I have three files: index.php, process.js, and redirect_process.php. The index.php serves as my homepage with a form embedded in it. Whenever the submit button is clicked, the process.js script is triggered to v ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further d ...

Assistance in using jQuery to locate specific div elements is

I am currently working on creating a navigation bar that features icons triggering contextual submenus upon hover. The main idea is that hovering over an icon will display a popup menu or tooltip with additional options, while still allowing the icon itsel ...

What is the best way to switch out src="name1" with src="name2"?

Hey everyone! I had this idea, but I'm struggling with how to bring it to life. Is there a way to ensure that when you press ctrl + shift + i or f12, a specific part of the html code changes? For example: changing SRC="video.MP4" to SRC="error.MP4" ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...