removeItem removing items from multiple lists

Link to the project or level: Code.org - App Lab
What I expect to happen: removeItem should only be removing the item at index 2 from list2
What actually happens: removeItem is removing the item at index 2 from both list1 and list2
What I’ve tried: list1 is copied to list2 to be used in a larger app, but removeItem is removing that item from both lists, for some reason. This is from a larger project, so I pulled just the relevant information and simplified it down to demonstrate what’s happening. Thanks!

This is the way Javascript works. Arrays in Javascript are objects. There is no array type variable it is just a variable that holds onto an Array object. When you assign a variable with an Array to another variable they hold onto the exact same Array object. It doesn’t matter which variable you use to modify the Array object there is only one Array.

1 Like

Thank you so much for your response! Seeing as the AP CSP curriculum doesn’t cover objects at all, I haven’t spent much time on them, so I was aware that Arrays are objects, but I didn’t realize that assigning them to another variable keeps the actual object linked. That’s so interesting!

Another consequence. In Javascript parameters are passed by value. So if you pass a number to a function and that function changes the parameter the originally passed variable is unchanged. However, if you pass an array you can change that array in a function and it is changed everywhere. It is still pass by value but the value is an object which can be changed.

1 Like

Thanks for the follow-up. That’s excellent to know! Your response has me going down a rabbit hole of reading up on objects and arrays and their methods this morning, which is really interesting and something we never cover in CSP, but I wish we did.

1 Like