Home > Blockchain >  Why does my function keep coming back as undefined?
Why does my function keep coming back as undefined?

Time:12-13

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.

CodePudding user response:

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

CodePudding user response:

You could use map also:

const incrementByOne = (arr) => arr.map((element) => element   1);

CodePudding user response:

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

CodePudding user response:

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)
  • Related