Add the sum of an undefined array in Javascript

897 Views Asked by At

I now this code works if I have preset values defined in my array, how would I go about doing this when the values are not defined? I have a hard time with all loops in general especially for loop.

I know there are methods to achieve this, but for the purpose of my assignment I must achieve it using a for loop.

function sum() {
  let input = document.getElementById("wordInput").value;
  let values = [];
  let sum = 0;

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

    if (values) {
      document.getElementById("resultReturned").innerHTML = " Total is" + sum;
    }
  }
}
3

There are 3 best solutions below

0
On

Give your function a parameter. This way you can pass any array to your function and loop over it, no matter the length.

function sum(values) {
  let input = document.getElementById("textField").value;
  let sum = 0;

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

    if (values) {
      document.getElementById("valueReturned").innerHTML = "The sum is" + sum;
    }
  }
}

// Call the sum function and pass an array.
sum([1, 2, 3, 4]);
0
On

Simple Example:

function sumup(values) {
  // Got rid of input
  // taking values as arguments for this example
  let sum = 0;
  let res = 0; // Or whatever the default value
  if (values) {
    for (var i = 0; i < values.length; i++) {
      sum += values[i]
      res = sum;
    }
  }
  document.getElementById("valueReturned").innerHTML = "The sum is " + res;
}
sumup([1, 2, 3, 4, 5]); // Array passed here
// 15
<div id="valueReturned"></div>

0
On

It's a little unclear what you're trying to solve but I'll answer the questions I believe you may be asking.

First, I'll provide a few comments on the code I'm seeing. For starters, you probably want to move that if (values) {} block out of the for loop. I'm guessing your intent is to update the DOM if there are values.

Second, if values is an array, you should look at the length of the array to determine if it is empty with something like if (values.length > 0). An empty array will evaluate truthy and the DOM would be updated every time with your code as written.

Third, I'm not sure about the role of input here. That will give you a single value, not an array.

Here's what I would recommend, not knowing what you envision for the role of input:

function sum() {
  let input = document.getElementById("wordInput").value;
  let sum = 0;

  const values = [] // wherever values come from, perhaps a function argument or inputs

  for (var i = 0; i < values.length; i++) {
    sum += values[i]
  }
  if (values.length > 0) {
    document.getElementById("resultReturned").innerHTML = "The sum is" + sum;
  }
}