Undefined value in last iteration to traverse nested array

Asked

Viewed 29 times

2

I made the following code with the intention of traversing the following array:

[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]

Everything is happening as I wanted, all array values are being displayed but the last console.log returns undefined, I don’t know why. The following code:

let vet = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];

function showNums(arr) {
    for(let i = 0; i < arr.length; i++){
      for(let j = 0; j < arr[i].length; j++){
        console.log(arr[i][j]);
      }
    }
}
  
console.log(showNums(vet));

1 answer

3


Its function does not return any value (it has none return within it). And in such cases, the "return" of it is undefined. Ex

function comReturn() {
    console.log('eu retorno um valor');
    return 1;
}
function semReturn() {
    console.log('eu não retorno nada');
}

let x = comReturn();
let y = semReturn();

console.log(x); // 1
console.log(y); // undefined

That is, the function showNums returns undefined, and how you had her return printed, the undefined is printed at the end.

Therefore, simply call the function, without printing the return:

let vet = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];

function showNums(arr) {
    for(let i = 0; i < arr.length; i++){
      for(let j = 0; j < arr[i].length; j++){
        console.log(arr[i][j]);
      }
    }
}

showNums(vet);

  • Thank you very much, my doubt has been successfully resolved!

  • @Saul44 If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem :-)

  • I’m trying to accept, the site asks me to wait at least 5 minutes, thanks again!

  • @Saul44 Oh yeah, I forgot you have this waiting time to accept... :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.