Credit Card Checker: Why is my function returning undefined after printing out the array backwards?

https://www.codecademy.com/practice/projects/credit-card-checker
I created a function to iterate backwards through an array and it works, but it keeps returning undefined before and after. Why?

const invalid5 = [5, 3, 8, 2, 0, 1, 9, 7, 7, 2, 8, 8, 3, 8, 5, 4];
function validateCred(array){
  let num = array.length;
  for (let i = num; i >= 0; i--){
    console.log(array[i]);
  }
}
console.log(validateCred(invalid5));

The output is then:

undefined
4
5
8
3
8
8
2
7
7
9
1
0
2
8
3
5
undefined

Notice how you have 2 undefined outputs. The first one is because you set:
num = array.length;
which means the first pass of your for loop will use i == 16 (beyond the scope of the array because arrays start counting at 0).

The second undefined is due to the fact that you are logging a function that doesn’t have a return statement. So when you call your function:

console.log(validateCred(invalid5));

Function validateCred doesn’t return anything, and so console.log() doesn’t have anything to log but undefined. Try calling your function without console.log() :+1:

I see… so does that mean I should change my code from:

num = array.length

to

num = array.length-1

?

yes! that way it won’t go beyond the length of the array.
Also, is there a reason you need it to go backwards?

Yes if you see the steps they want me to iterate left through an array (iterating backwards).

Ok, I was going to add that there’s the array method .reverse() (MDN Documentation) that might help you as well.

const coolArray = [1,2,3,4,5];
coolArray.reverse();
console.log(coolArray); //output: 5,4,3,2,1

With that in mind, you could do:

for(let i = 0; I < array.length ; i++){
  //your code
} 

Just keep in mind that like the documentation says, .reverse() will modify your original array!

Oh wow! Thanks for making my life easier, unfortunately, they want me to use a method that’s non-destructive.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.