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

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

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 Relatório

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 Relatório

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 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