0
 const student1 = {
  id: 1,
  name: "Reed",
  subjects: [],
  addSubject(subject) {
    this.subjects = this.subjects.push(subject); //what's wrong with this line
  }
}



student1.addSubject('Math');
console.log(student1.subjects); 

// logs out 1 instead of ['Math'], .push isn't functioning properly

ridam
  • 1
  • [Array.push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) is meant to return the new length of the array; what makes you think otherwise? If you want the array itself, log the array itself. Or simply use `this.subjects.push(subject)` rather than setting `this.subjects = ...` – mykaf Oct 17 '22 at 19:39

2 Answers2

0

 const student1 = {
  id: 1,
  name: "Reed",
  subjects: [],
  addSubject: function(subject)  {
    this.subjects.push(subject);
  }
}



student1.addSubject('Math');
console.log(student1.subjects); 
Haim Abeles
  • 982
  • 6
  • 19
0

Array.push() returns the new length of the array, not the array itself.

Unless you have a reason to capture this value, you don't need to assign it:

addSubject(subject) {
    this.subjects.push(subject);
}
esqew
  • 42,425
  • 27
  • 92
  • 132