Credit Card Checker Project - Array is mutated within the function?

Hi guys,
I got stuck on the Credit Card Checker Project:
https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-challenge-project-credit-card-checker/projects/credit-card-checker

Here is my code: https://gist.github.com/michaelarie96/eea621f3d4a976809a2a8b95e58b0216

Every thing seems ok with my code, I checked it thoroughly, but for some reason the function validateCred is mutating the parameter array which is called with the function, even though it’s not used or returned in the end:

const validateCred = arr => {
    const checkedArray = arr;
    for (let i = checkedArray.length - 2; i >= 0; i -= 2) {
        checkedArray[i] *= 2;
        if (checkedArray[i] > 9) {
            checkedArray[i] -= 9;
        }
    }
    const checkedNumber = checkedArray.reduce((acc, currValue) => acc + currValue);

    if (checkedNumber % 10 === 0) {
        return true;
    } else {
        return false;
    }
}

You can see in the original code that I checked the array with a console.log on line 46 (before the function is called) and on line 52 (after the function was called), and the array is unfortunately mutated.

Any guidance would be appreciated. Thanks :slight_smile:

this:

const checkedArray = arr;

does not make a copy of your array. Now you have two variables pointing the the same array in memory

Lets say you have a house (apartment, whatever, doesn’t matter) you can hand out your address to two friends (the variables in this analogy), now both your friends can find your house (the array in this analogy), but there is still only one house.

so if you change something in your house (array), both your friends will notice this when they come visit.

1 Like

Understood, thank you.
So how do I assign the value of arr to checkedArray, instead of just pointing to the same array?

You would need to make a copy of the array. There are a variety of ways to copy an array.

But that is something that can be found with a little help from a search engine. You don’t need me for that

Good to know. Thank you! :smiley: