Credit Card Checker: Original array is changed when pushed

Hello!
Here’s a link to my code: credit_card_checker/main.js at master · auskr4/credit_card_checker · GitHub

My validateCred() function seems to work and correctly identify the arrays as valid or invalid.
Then, inside the findInvalidCards() function, when I push the invalid arrays into the invalidCards array, the arrays are changed by the validateCred() function.

Can anyone explain why the array I push in findInvalidCards() is the modified array?

Link to exercise: https://www.codecademy.com/paths/back-end-engineer-career-path/tracks/becp-22-javascript-syntax-part-ii/modules/wdcp-22-credit-card-checker/projects/credit-card-checker

Thanks!
Austin

in your validateCred function, you have:

function validateCred(arr) {
    /* splice out value @ last index, reverse array, then double every every even index */
    let arrsplrev = []; 
    let spliced = arr.splice(-1, 1);
    arrsplrev = arr.reverse(); //spliced and reversed 

Note that in your code, .splice() and .reverse() modifies the original array, arr.
You may want to make a copy of the array parameter and work with that instead:
One way to do that is to use Array.from() ;
but just doing = won’t work because an array is a kind of object.

function validateCred(numbers) {
    const arr = Array.from(numbers);
    /* splice out value @ last index, reverse array, then double every every even index */
    let arrsplrev = []; 
    let spliced = arr.splice(-1, 1);
    arrsplrev = arr.reverse(); //spliced and reversed 

Note that having an object as a parameter for a function is tricky:
the function can change the object that its called on.

1 Like

This worked, thank you! I was trying to do something similar after I posted here but Array.from() works better.

Thanks again!