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

184
Views
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 answers
Answer question

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 Report

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 Report

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