0

Iam a beginner and just starting with JS. Please forgive me if this is a stupid question.

After pushing a value into an array nested in an object. It shows the number of items in the array but the values are undefined rather than displaying the new array when i console log.

const warrior = {
  health: 100,
  equipment: ["sword", "sheild"],
  location: {
    x: 0,
    y: 0,
  },
  walk: function(a, b) {
    warrior.location.x = warrior.location.x + a;
    warrior.location.y = warrior.location.y + b
  },

  strike: function(c) {
    warrior.health = warrior.health - c
  },

  pickMeUp: function(equip) {
    warrior.equipment = warrior.equipment.push(equip)
  }


}
warrior.pickMeUp("axe");
console.log(warrior.equipment);
//undefined
//3

Im not sure why this is happening? Does this have anything to do with the way i wrote the function? writing it as >>

pickMeUp:function(equip){
            this.equipment.push(equip)

removes - undefined

but, it still only returns array length and not the values.

Bartman88
  • 11
  • 1
  • You can't modify a `const`. – Wais Kamal Jan 07 '21 at 22:21
  • `push` mutates the existing array, so it is already a code smell that you would want to assign it back to itself. If `push()` returned the whole array, the assignment would do nothing. – Taplar Jan 07 '21 at 22:22
  • @WaisKamal `warrior` is a constant. `warrior.equipment` is not. – Taplar Jan 07 '21 at 22:22
  • @Taplar Im not sure what you mean by code smell. Can you please elaborate your explanation? – Bartman88 Jan 07 '21 at 22:31
  • https://en.wikipedia.org/wiki/Code_smell <= A code smell is when you read a bit of code and you get the feeling that something isn't quite right, or doesn't make sense. – Taplar Jan 07 '21 at 22:32
  • Read the linked answers to the question and ask why it solves this problem. If that doesn't work, try removing `warrior.equipment = ` from the line in which it occurs and wonder why it suddenly started working :-) – traktor Jan 08 '21 at 03:25

0 Answers0