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

189
Vistas
Why does my function keep coming back as undefined?

Here is the code I have. I am pretty new to javascript still so I don't see why adding the function stops the for statement from incrementing the integers.

const arr = [10,10,16,12]

function incrementByOne(arr) {
  // arr is an array of integers(numbers), Increment all items in the array by
  // return the array


for (const i = 0; i < arr.length; i++){
  arr[i] += 1;

  
}
return arr
}

Any help would be greatly appreciated.

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

0

const arr = [10,10,16,12]

function incrementByOne(arr) {
    // arr is an array of integers(numbers), Increment all items in the array by
    // return the array


    for (let i = 0; i < arr.length; i++){
        arr[i] += 1;
    }
    return arr
}
let a = incrementByOne(arr)
console.log(a)
about 4 years ago · Juan Pablo Isaza Denunciar

0

I ran your code under Node.js:

Code:

'use strict';

const arr = [10,10,16,12]

function incrementByOne(arr) {
    for (const i = 0; i < arr.length; i++) {
      arr[i] += 1;
    }
    return arr
}

console.log(incrementByOne(arr));

Output:

$ node incr.js
incr.js:6
        for (const i = 0; i < arr.length; i++){
TypeError: Assignment to constant variable.
    at incrementByOne (incr.js:6:37)
$

As you can see, it complains that you are trying to change the value of i which your code said was constant. Write let i = 0 for a non-constant value.

Code:

'use strict';

const arr = [10,10,16,12]

function incrementByOne(arr) {
    for (let i = 0; i < arr.length; i++) {
      arr[i] += 1;
    }
    return arr
}

console.log(incrementByOne(arr));

Output:

$ node incr.js
[ 11, 11, 17, 13 ]
$ 
about 4 years ago · Juan Pablo Isaza Denunciar

0

You should use let i = 0 instead of const i= 0 to initilize the loop iteration counter i

const arr = [10,10,16,12]

function incrementByOne(arr) {
  // arr is an array of integers(numbers), Increment all items in the array by
  // return the array


for (let i = 0; i < arr.length; i++){
  arr[i] += 1;

  
}
return arr
}

Then call incrementByOne function

incrementByOne(arr);
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