0

const calculateBMI = function (weight, height) {
   let BMI = weight / height ** 2;
   return BMI;
};

const marksData = {
   height: 1.69,
   weight: 78,
   msBMI: calculateBMI(this.weight, this.height),
};

const johnsData = {
   height: 1.95,
   weight: 92,
   jsBMI: calculateBMI(this.weight, this.height),
};

console.log(marksData.msBMI);
console.log("something");
console.log(johnsData.jsBMI);

I don't know why the output of the function "const calculateBMI" inside two objects ("marksData" and "johnsData") is NaN, the problem I see here, is that the object:

const marksData = {
   height: 1.69,
   weight: 78,
   msBMI: calculateBMI(this.weight, this.height),
};

is not catching a value of :

height: 1.69,
weight: 78,

like something is wrong whit this syntax (this.weight, this.height)

David
  • 208,112
  • 36
  • 198
  • 279
  • You can't use `this` in an object literal to refer to the object being created, for two reasons: 1. It doesn't exist yet, and 2. There's no scope change that would allow `this` to have a different value than it does in the scope where the object literal is written. (The value of `this` is fixed in any given scope.) See the linked question's answers for details. You'll need to add the BMI after creating the objects, or calculate the BMI first and *then* create the objects (probably, in both cases, by creating a function to build the objects). – T.J. Crowder Jan 05 '23 at 14:51

0 Answers0