Credit Card checker returning invalid card numbers but

Hi,

I am currently doing the credit card checker and am running into an issue where findInvalidCards() is returning the correct invalid numbers, but it is showing the reversed array after every other number has been multiple by 2. I don’t get what i did wrong. I saved to different variables and am not getting any changes. Can anyone help? My code is below:

In JavaScript, some data types such as strings and numbers are immutable, whereas objects and arrays are mutable. You can mutate/modify the object/array without creating a new object/array from scratch.

The issue is with this line:

let checkArr = arr;

You think that you have created a copy of arr and assigned it to checkArr. But, that is not what happens. Both checkArr and arr point to the same memory address i.e. both variables refer to the same array. If you modify/mutate arr, then checkArr will also be changed. Similarly, if you change checkArr, you are changing arr as well because both variables point to the same array.

In your code, when you pop and reverse checkArr. you are changing the original arr array. To make a copy of the array, see this stackoverflow thread.

One of the methods mentioned in the thread is the use of spread syntax.

// Your code:
let checkArr = arr;

// Change it to:
let checkArr = [...arr]; 

Now, popping and reversing checkArr will not affect arr.

Thanks for the descriptive answer! I ended up finding out that i could use .splice() to do the same. I knew i was changing arr but didn’t know how to approach it / ask the exact question.

Thank you!!!

1 Like

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