Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Why is the following for-loop for a running sum returning undefined?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!