AppLab Issue with Lists?

Can someone tell me if this scenario is a mistake on my part or a glitch with AppLab?

  1. I set a variable called classList, containing a list of names of students.
    var classList = [“student1”, “student2”, … ];
  2. I assigned this variable to originalList.
    var originalList = classList;
  3. I then manipulate originalList in various ways.

Am I right to assume that classList should stay the same after this? Right now I have a program where it changes when I change the originalList, and I don’t know why.

Hi -
Your assumption that
var originalList = classList
will make a copy of the original array is incorrect.
What this does is to create a new variable that refers to the same array as the original.
It sounds like your intention is to make a copy of the originalList array.
This video shows some ways to do that…
https://www.youtube.com/watch?v=EeZBKv34mm4

Thanks Mitch.

I fixed it with a simple traversal to create the new list.

One thing that has not been asked is why do you need a second copy?

Instead of making a copy so you can change it, create a new list as you make changes.

I want that list to be accessible and unchanged for other functions as the app is used.

I would recommend taking a page out of the Functional Programming Paradigm. Any function that modifies a list will take a list as a parameter and return a newly created list with the changes leaving the parameter alone.

When you call the function you can decide what to do with the new list. What this does is set up lists to be immutable (never change unless you explicitly assign.) In general, that will lower the number of errors encountered in sharing lists between functions.

classList.slice() to make a copy of it:

var originalList = classList.slice()

var originalList = classList does not create a copy of it, but puts classList into originalList, and when you will modify classList, originalList will change. The same thing happens with originalList.

I want to thank everyone who has responded. My grasp of this is tenuous, but I did grab incites from everyone’s feedback if not a whole understanding of how to apply it to my problems and project.

It definitely encourages me to post more to this forum when I know I can define my problem well enough.

I’ll be honest I did not think this occurred normally until it happened to me in my own project!

I had to set the new array to Array.from(oldArray)

That is weird though how it happens.