# Credit Card Checker: Array Modification and Definition Issue

Hi! In the Credit Card checker task I stumbled upon an issue with modifying arrays. Below in the code I have modCardNumber array that I defined as equal to cardNumber. I would then modify modCardNumber with the loops. In the end to check, I print both arrays and see how modCardNumber has changed. However, cardNumber is now the same as modCardNumber. Why is that happening? I think, I haven’t fully understood variable definitions in prior lessons, but not sure.

``````// All valid credit card numbers
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];

function validateCred(cardNumber) {
let modCardNumber = cardNumber;
for (let i = modCardNumber.length-2; i >= 0; i -= 2) {
modCardNumber[i] *= 2;
if (modCardNumber[i] > 9) {
modCardNumber[i] -= 9;
}
}
console.log(cardNumber.join(''));
console.log(modCardNumber.join(''));
}

validateCred(valid1);
``````

i am not sure this issue has been covered at this point, but this line:

``````let modCardNumber = cardNumber;
``````

works different then you expect.

Seems you got pretty far figuring out what the problem is:

that is because both variable point to the same array in memory. So you only have one array. Here is a simple example to help you grasp it:

``````const one = ['a', 'b', 'c'];
const two = one;

console.log(one, two);
one[0] = 'd';
console.log(one, two);
two[1] = 'e';
console.log(one, two);
``````

anyway, here:

``````let modCardNumber = cardNumber;
``````

you need to make sure you copy the array.

you could practice this with the simple example i provided

just for myself, the project url: https://www.codecademy.com/practice/projects/credit-card-checker, so i can find the project more easily next time, might i need to help you further

1 Like

Hi stetim94! Thank you very much for the thorough explanation. The simple phrase of ‘cope the array’ guided me directly to:

`let modCardNumber = cardNumber.slice();`

I am not sure that this is the best way to do it, but seems to solve the problem you described.

Thanks again!

you’re welcome

given you use es6, i would use the spread operator:

``````let modCardNumber = [...cardNumber];
``````

`.slice()` seemed to be the way to go before es6.

the spread operator (at least to me) is clearer in the fact that you create a new array.

1 Like

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