Home > Software design >  Why is the following for-loop for a running sum returning undefined?
Why is the following for-loop for a running sum returning undefined?

Time:06-07

was wondering why this for loop was returning undefined? Trying to return the running sum of the array.

var runningSum = function(nums) {
 let i  
  for (i = 1; i < nums.length; i  ) {
  nums[i]   nums[i-1]
 }
 };

EDIT: I got rid of the return but it's still outputting undefined

CodePudding user response:

The fundamental error is not returning the result from the function.

But also you must understand that nums is an array and passed by reference and therefore the function is modifying the input argument, in which case the return value might not actually be needed/intended.

Consider the following which prints both the return value AND the original input after the function call.

const runningSum = function(nums) {
  for (let i = 1; i < nums.length; i  ) {
    nums[i]  = nums[i-1]
   }
   return nums
 }
 
 
const input = [ 1, 1, 1, 1 ]

console.log(runningSum(input))
console.log(input)

  • Related