본문 바로가기

Programming/JavaScript

Coding Challenge #3 - comparing BMIs using objects

Tried 👏👏👏

const Mark = {
    fullName: 'Mark Miller',
    mass: 78,
    height: 1.69,

    calcBMI: function () {
        this.bmi = this.mass / (this.height * this.height);
        return this.bmi.toFixed([1]);
    }
}

const John = {
    fullName: 'John Smith',
    mass: 92,
    height: 1.95,

    calcBMI: function () {
        this.bmi = this.mass / (this.height * this.height);
        return this.bmi.toFixed([1]);
    }
}

function compareBmi() {
    whoHasHigherBmi = Mark.calcBMI() > John.calcBMI() ? `Mark's BMI (${Mark.calcBMI()}) is higher than John's BMI (${John.calcBMI()})!` : `John's BMI (${John.calcBMI()} is higher than Mark's BMI (${Mark.calcBMI()})!`
    return whoHasHigherBmi;
};

console.log(compareBmi());
// Mark's BMI (27.3) is higher than John's BMI (24.2)!

 

Answer

const mark = {
    fullName: 'Mark Miller',
    mass: 78,
    height: 1.69,
    calcBMI: function () {
        this.bmi = this.mass / this.height ** 2;
        return this.bmi;
    }
};

const john = {
    fullName: 'John Smith',
    mass: 92,
    height: 1.95,
    calcBMI: function () {
        this.bmi = this.mass / this.height ** 2;
        return this.bmi;
    }
};

mark.calcBMI();
john.calcBMI();

console.log(mark.bmi.toFixed(1), john.bmi.toFixed(1)); // prints 27.3 24.2

if (mark.bmi > john.bmi) {
    console.log(`${mark.fullName}'s BMI (${mark.bmi.toFixed(1)}) is higher than ${john.fullName}'s BMI (${john.bmi.toFixed(1)})`)
} else if (john.bmi > mark.bmi) {
    console.log(`${john.fullName}'s BMI (${john.bmi.toFixed(1)}) is higher than ${mark.fullName} 's BMI (${mark.bmi.toFixed(1)})`)
} // Mark Miller's BMI (27.3) is higher than John Smith's BMI (24.2)

'Programming > JavaScript' 카테고리의 다른 글

Looping Arrays, Breaking and Continuing  (0) 2022.09.19
Iteration: The for Loop  (0) 2022.09.15
Object Methods  (0) 2022.09.15
Dot vs. Bracket Notation  (0) 2022.09.11
Introduction to Objects  (0) 2022.09.11