-2

const markMiller = {
  firstname: 'Mark',
  secondName: 'Miller',
  mass: 78,
  height: 1.69,
  calcbmi: function () {
    this.bmi = this.mass / this.height ** 2;
    return this.bmi;
  },
};
const johnSmith = {
  firstname: 'john',
  secondName: 'Smith',
  mass: 92,
  height: 1.95,
  calcbmi: function () {
    this.bmi = this.mass / this.height ** 2;
    return this.bmi;
  },
};
console.log(typeof (johnSmith.bmi))
console.log(markMiller);

Why bmi is added as attribute and show as undefined ? I also tried to add the attribute with '[]' notation but the result was same.

derpirscher
  • 14,418
  • 3
  • 18
  • 35
Kaiser
  • 39
  • 4
  • 2
    You code does not call the `calcbmi()` function. – Pointy Nov 17 '22 at 15:11
  • 2
    Because you are not calling the function that calculates the bmi ... – derpirscher Nov 17 '22 at 15:11
  • Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Ivar Nov 17 '22 at 15:15

1 Answers1

1

You don't define a attribute called bmi in this code snippet. You'll have to add it while creating like this:

const johnSmith = {
  firstname: 'john',
  secondName: 'Smith',
  mass: 92,
  height: 1.95,
  bmi: 12345 // HERE
  calcbmi: function () {
    this.bmi = this.mass / this.height ** 2;
    return this.bmi;
  },
};

or if you want to calculate it using your function you'll have to call

johnSmith.calcbmi()

Now you can access johnSmith.bmi

JaRoMaster
  • 428
  • 1
  • 3
  • 26