Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda