JavaScript - Sum of array values without using a loop

← PrevNext →

One of the easiest way to get the sum of array values without looping is to use the .reduce() method. The method reduces array elements into a single value. Most importantly, it reduces the size of the script, since you don't need to loop through each element or do any recursion.

➡️ Learn more about reduce() method

Here's an example.

<script>
  const calculate = () => {
    //  sum without looping (using reduce method)
    const arr = [5, 20, 93, 38, 11].reduce((prev, cur) => prev + cur);
    document.write(arr);     // Output: 167
  }

  calculate();
</script>
Try it

Remember: The "reduce()" method does not change the original array. The elements (or values) remain the same.

➡️ JavaScript Methods

Here's a jQuery script that uses $.each() method to get the sum of array values. It loops through each element and returns the sum.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  const calculate = () => {
    const arr = [5, 20, 93, 38, 11];
    let t = 0;
    
    //  sum using a loop (using jQuery each)
    $.each(arr, function (index, value) {
      t = t + value;
    });

    document.write (t);        // Output: 167
  }

  calculate();
</script>

← PreviousNext →