Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
- Write a function called sumNumbers that accepts a single array of numbers and returns the sum of the numbers in the array

I'm really new to JavaScript, So excuse me if this question might seem a little underwhelming.

I'm trying to write a function that performs the following:

1. accepts a single array of numbers and returns the sum of the numbers in the array. 2. If empty, returns 0.

let num3 = function sumNumbers([index]) {
if (index != "number") {
    return 0;
}
else {
    [index].reduce((a, b) => a + b, 0)
}


}



num3(1, 2, 3);

However, I am getting this error :

Uncaught TypeError: number 1 is not iterable (cannot read property Symbol(Symbol.iterator))
at sumNumbers (main.js:16:31)
at main.js:25:1

Anyone know the solution? would really appreciate it :)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can iterate over the array using a for loop and increment the sum in each iteration and finally return it.

If there are no numbers in the array then the function would return the initial value of sum, which is 0.

function addNums(nums) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }
  return sum;
}

console.log(addNums([1, 2, 3]));
console.log(addNums([]));

You can also use Array.prototype.reduce and do the calculation in a single step.

const addNums = (nums) => nums.reduce((s, n) => s + n, 0);

console.log(addNums([1, 2, 3]));
console.log(addNums([]));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda