All.
I am currently working in JS. My question concerns objects and the 'this' keyword. Please see my code below:
function calcBMI(mass, height) {
return (mass / (height^2))
};
var Mark = {
firstName: 'Mark',
lastName: 'Jones',
height: 1.82,
mass: 81.64,
BMI: calcBMI(this.mass, this.height)
};
var John = {
firstName: 'John',
lastName: 'Rivera',
height: 1.79,
mass: 82.19,
BMI: calcBMI(this.mass, this.height)
};
function displayData() {
console.log('Mark\'s BMI: ' + Mark.BMI + ', ' + 'John\'s BMI: ' + John.BMI);
if (Mark.BMI > John.BMI) {
console.log('Mark\'s BMI is higher.')
} else if (John.BMI > Mark.BMI) {
console.log('John\'s BMI is higher.')
} else {
console.log('John and Mark have equal BMIs.')
}
};
displayData();
The task is to use the 'this' keyword to calculate the Body Mass Indexes of two people - John and Mark, expressed by the 'Mark' and 'John' objects. The property of BMI for each object is calculated with the 'calcBMI' function, at the top.
I am expecting the function to be called whenever the Object.BMI is invoked.
Instead, the result is NaN. Specifically, the output is:
Mark's BMI: NaN, John's BMI: NaN
John and Mark have equal BMIs.
Please help me to understand just where I have gone wrong. Thank you.
PS - This is my first StackOverflow question. If you have any feedback on how I may better ask questions, here, I would appreciate it. Also, my code at times has an ugly look. I happily take suggestions making it more legible and beautiful as well.