A BMI calculator function that provides results in string format

Currently, I am enrolled in an online course where one of the tasks given is to develop a BMI (body mass index) calculator. The objective is to create a program that can calculate a user's BMI and provide them with their specific BMI category based on the result.

In my attempt to tackle this problem, I initially implemented an if statement within my code. However, after testing it out, the validator flagged my solution as incorrect. Could someone kindly review my code to help pinpoint any potential errors?

var interpretation = "";

function bmiCalculator(weight, height) {
    var bmi = weight / Math.pow(height, 2);

    if (bmi < 18.5) {
        interpretation = "Your BMI is " + bmi + ", so you are underweight";
    } else if (bmi >= 18.5 && bmi <= 24.9) {
        interpretation = "Your BMI is " + bmi +", so you have a normal weight";
    } else {
        interpretation = "Your BMI is " + bmi + ", so you are overweight";
    }

   return interpretation;
}

Answer №1

To get the final output, you have to utilize Template strings or string concatenation to include the bmi value.

Here is a demonstration using Template strings:

var interpretation = "";

function calculateBMI(weight, height) {
    bmi = weight / Math.pow(height, 2);

    if (bmi < 18.5) {
        interpretation = `Your BMI is ${bmi}, indicating that you are underweight`;
    } else if (bmi >= 18.5 && bmi <= 24.9) {
        interpretation = `Your BMI is ${bmi}, which shows a normal weight range`;
    } else {
        interpretation = `Your BMI is ${bmi}, suggesting that you are overweight`;
    }

    return interpretation;
}

Your code can be enhanced further with this modification

function calculateBMI(weight, height) {
    let bmi = weight / Math.pow(height, 2);
    let interpretation = `Your BMI is ${bmi}, therefore you `
    if (bmi < 18.5) {
        interpretation += `are underweight`;
    } else if (bmi < 25) {
        interpretation += `have a normal weight`;
    } else {
        interpretation += `are overweight`;
    }

    return interpretation;
}

Answer №2

In conclusion to the previous statements, here is a simple solution that achieves the same outcome:

function calculateBMI(weight, height) { 
  var bmi = weight/(height*height);
  var roundedBmi=bmi.toFixed(2);
  return `Your BMI is ${roundedBmi}, so you `+
       (bmi<18.5?'are underweight'
      : bmi<25  ?'have a normal weight'
      :          'are overweight'); }

I included rounding to two decimal places using .toFixed(2) since nobody needs an answer with such precise accuracy.

Although Math.pow(height,2) is theoretically correct, the direct multiplication height*height is more efficient and takes less effort to calculate.

(While it may not make a difference in this scenario, it can be significant when dealing with multiple iterations or large arrays.)

Answer №3

After much trial and error, I finally cracked the code using this method:

function calculateBMI(weight, height) {
    var bmi = weight / (height * height);
    if (bmi > 24.9){
        return "Your BMI is " + bmi + ", indicating you are overweight.";
    }
    if (bmi >= 18.5 && bmi <= 24.9){
        return "Your BMI is " + bmi + ", suggesting a healthy weight.";
    }
    if (bmi < 18.5){
        return "Your BMI is " + bmi + ", meaning you are underweight.";
    }
}

It's fascinating how crucial the order of the if statements can be in situations like this!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically Inject HTML with Drag-and-Drop Interaction

Looking for an easy method to move html elements or content around on a webpage? The objective is to drag the element and release it onto a designated area. After dropping the element, customized html content will be added dynamically depending on ...

What is the best way to pass a context to the function constructor?

After reading about the dangers of using the eval method, I decided to utilize a function constructor to prevent any malicious code injection. Here is the approach I took: function evalContext(context: Record<string, unknown>) { const injectCon ...

Vue.js running locally does not trigger the ready function

When running the following code in jsfiddle, there are no issues. However, when attempting to run it on localhost, the ready function does not fire and the ordered list items are not displayed. How can this be resolved? index.html <body> <h3&g ...

Slow CSS :hover animations in the most recent release of Chrome

I recently upgraded my browser from chromium version 67 to the latest Chrome version 79. However, I noticed that after the upgrade, the CSS transitions on my website have become very laggy and unresponsive. Surprisingly, everything works perfectly fine on ...

Combating React SetState Race Conditions with the Power of Promise.all

componentDidMount() { Promise.all([OfferCreationActions.resetOffer()]).then( () => { OfferCreationActions.updateOfferCreation('viewOnly', true); OfferCreationActions.updateOfferCreation('loadingOffer', true); ...

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Preserve the font awesome icon when the page is refreshed

My code successfully toggles the visibility of forums on my webpage. Although the status show/hide is retained after reloading the page, I have an issue with the font awesome icon reverting back to default. How can I modify the code to ensure that the f ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Leveraging the On Keyup Function in Real-Time

How can I modify this code to run after an ajax call using .live method? var element=document.getElementById('txt_url'); element.onkeyup=function(){ var input=element.value; if(input=='') return; if(input.indexOf('h ...

What are some methods for extracting a value from a separate webpage and saving it as a variable in my code?

I am utilizing graphite to obtain statistics and would like to display a justgage gauge for a specific variable. Graphite provides values in either JSON format: [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}] o ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

What is the process to retrieve a function from a router javascript file using node.js?

Dealing with a web application that is not my own, I now have the task of sending out one hundred emails. Unfortunately, the code is poorly documented and written, which means I need to test it to figure out what I can and cannot do. However, I'm uns ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

Intersecting object identification, fresh Function

I'm currently utilizing the "Sinova / Collisions" library on GitHub along with Node.js. The library can be found at https://github.com/Sinova/Collisions. I am in need of a function that allows me to delete all data at once, as the current function for ...

When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude f ...

Unable to retrieve the form from the website

My goal is to extract the login form from: Although I can see the form element when inspecting in Chrome, I'm encountering difficulties retrieving it using the jaunt API in Java. userAgent = new UserAgent(); userAgent.visit("https://etoro.com/login" ...

Converting objects to arrays in Typescript: A step-by-step guide

Can anyone assist me in converting a string to a Typescript array? Any help would be greatly appreciated. Take a look at the following code snippet: private validateEmptyOption(): any { console.log("CHECKED") let isValid = true; this.currentF ...

Updating the quantity of a Stripe subscription in Node.js: A Step-by-Step Guide

I'm having trouble modifying the quantity of items in an existing Stripe subscription. Whenever I attempt to update it, I encounter the following error: "error": { "message": "Invalid array", "param": &q ...

Should custom directives be utilized for templating within AngularJS applications?

Thinking about optimizing my AngularJS app, I'm considering creating custom directives for the navigation bar and footer which appear on every page. This way, I can easily modify them without having to update each individual html file. Do you think th ...