0

Not sure what the title should be really, but I was working on a project but came across this error, so I made a simple representation of it: When i instantiate a new object (The student), the student has a certain number of classes, AFTER initializing this object I then add another class to the list of classes, which then is passed to a new student object. When I output their classes the console says they have the same number of classes, I just do not understand why "student1" seems to update their list AFTER it was started, can somebody help? (init is ran when HTML Body is loaded)

function init() {

  let newList = [];

  newList.push(new Class("Maths"));
  newList.push(new Class("English"));

  let student1 = new Student("Bob", "1", "2", newList);

  let newList2 = newList;
  newList2.push(new Class("Science"));

  let student2 = new Student("Bob", "2", "1", newList2);

  console.log(student1.list);
  console.log(student2.list);

}

class Student {

  constructor(firstName, lastName, age, classes) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.list = classes;
  }

}

class Class {

  constructor(subject) {
    this.subject = subject;
  }

}
John Costa
  • 11
  • 1
  • 2

1 Answers1

0

I think your issue is this line:

let newList2 = newList;

According to the situation your describe you want to copy the array.
But with this line you're just assigning it to another variable instead of copying.
So in fact, without copying, the lists of both instances are the same.
In order to copy just so something like this:

let copy = array.slice(0);
/* or (will not work for large arrays)  */
let copy = [...array]; 
WolverinDEV
  • 1,494
  • 9
  • 19
  • What I'm confused about is why does me assigning this new variable then cause the first object to gain another class which was pushed to this new variable. Same problem happens if I keep the array, create an object, push and item and create another item. – John Costa Apr 12 '20 at 17:04
  • Well by classes I guess you mean objects (in your case class instances) the list right? So since `newList2` and `newList` are the same, adding elements to `newList2` is equal to adding elements in `newList`. Since both students have the same list, you'll get the same result. Some more info could be found here: https://stackoverflow.com/questions/7486085/copy-array-by-value?noredirect=1&lq=1 – WolverinDEV Apr 12 '20 at 17:09