javascriptarraysfunctionsum

Calculate sum of elements in an array within a function


I'm doing a prework for a course I'm going to attend and I have to complete some ex. I started learning JS last week so I'm a newbie and in this ex I don't have to use any method that allows me to calculate the sum. I only have to use logic. (for loops-functions-switch)

This is the ex: Define a function that will receive an array as an argument and calculate a sum of all its elements. For example, if we pass the following array to that function: const prices = [5, 7.99, 9.99, 0.99, 21], it should return 44.97 as output. How would you concatenate $ sign in front of the sum?

I don't really know how to do that sum, in fact the code I've written is totally wrong but I'd like to understand the logic behind.

function calculator (someArray) {
  let result;
  for(let i=0; i<= someArray.length; i++) {
    console.log(someArray[i]);
  }
  result=someArray[i] + someArray[i+=1];
}

const prices = [5, 7.99, 9.99, 0.99, 21];

calculator(prices);

I've now changed the code but it only prints the first 2 elements of the array:

function calculator (someArray) {
  let result;
  for(let i = 0; i<= someArray.length; i++) {
    result = someArray[i] + (someArray[i+=1]);
    console.log(result);
    return result;
  }
}

const prices = [5, 7.99, 9.99, 0.99, 21];

calculator(prices);

Solution

  • This is the ex: Define a function that will receive an array as an argument and calculate a sum of all its elements. For example, if we pass the following array to that function: const prices = [5, 7.99, 9.99, 0.99, 21], it should return 44.97 as output. How would you concatenate $ sign in front of the sum?

    Javascript has a nice feature: reduce

    function calculator (someArray){
      return someArray.reduce((howMuchSoFar,currentElementOfTheArray) => {
        howMuchSoFar = howMuchSoFar + currentElementOfTheArray;
        return howMuchSoFar;
      });
    }
    
    const prices = [5, 7.99, 9.99, 0.99, 21];
    
    console.log("$"+calculator(prices));

    (intentionally verbose)

    Going back to your original code (a classic for loop)

    function calculator (someArray){
      let result=0;
      for( let i = 0; i< someArray.length; i++){  
        result = result + someArray[i];
      }
      return result;
    }
    
    const prices = [5, 7.99, 9.99, 0.99, 21];
    
    console.log("$"+calculator(prices));