Javascript program to find the sum of elements in a sequence up to a given range.

  • From the above program we need to ensure that the range should not exceed the length of the array. If it is exceeding we will assign the range to the array length.
  • Given range is 5. So the sum of first five elements should calculate as 4 + 7 + 6 + 1 + 2 which is equal to 20.

We can also write this program by using slice and reduce methods as follows

  • Here arr.slice(0, range) extracts the elements from 0 to 5. i.e, [4, 7, 6, 1, 2];
  • reduce method starts with an initial value of 0 and adds each number to the accumulator and returns 20 as the output.

Leave a comment