I wrote the following code. Instead of giving me an answer, it outputs NaN. I would like the code to return the weights of John and Mark. Please explain.
'use script';
//  Declaring variables
var infoJohn;
var infoMark;
var bmiCalculator;
var higherBmi;
bmiCalculator = function (height, mass) {
    var calculatedBmi;
    calculatedBmi = mass / (height * height);
    return calculatedBmi;
};
infoJohn = {
    name: 'John',
    mass: 85,
    height: 110,
    bmi: bmiCalculator(this.height, this.mass)
};
infoMark = {
    name: 'Mark',
    mass: 120,
    height: 85,
    bmi: bmiCalculator(this.height, this.mass)
};
console.log('Mark\'s BMI: ' + infoMark.bmi, 'John\'s BMI: ' + infoJohn.bmi, 
'\n\n');
                A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
JavaScript is Object-Based, not Object-Oriented. The difference is that Object-Based languages don't support proper inheritance, whereas Object-Oriented ones do. There is a way to achieve 'normal' inheritance in JavaScript (Reference here), but the basic model is based on prototyping. Save this answer.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
You need to wrap bmiCalculator call to a function because otherwise this refers to a global (window) context.
This should work:
var bmiCalculator = function(height, mass) {
  var calculatedBmi;
  calculatedBmi = mass / (height * height);
  return calculatedBmi;
};
var infoJohn = {
  name: 'John',
  mass: 85,
  height: 110,
  bmi: function() {
    return bmiCalculator(this.height, this.mass);
  }
};
var infoMark = {
  name: 'Mark',
  mass: 120,
  height: 85,
  bmi: function() {
    return bmiCalculator(this.height, this.mass);
  }
};
//higherBmi = function (h)
console.log('Mark\'s BMI: ' + infoMark.bmi(), 'John\'s BMI: ' + infoJohn.bmi(),
  '\n\n');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With