0

I am a complete newbie. But I am working on a piece of training code and hit a wall. I completed the project, however, I wanted to test an additional piece of code. I want to use string interpolation to show the user a message like this:

If this object were on ${planetName} it would weight ${thisMuch}.

But I am confused on how to call only one argument from a function with two parameters.

function calculateWeight(earthWeight, planet) {
    let weight;
    if(planet === 'Mercury') {
    weight = earthWeight * .378
    return `${weight}`
    }if(planet === 'Venus') {
    weight = earthWeight * .907
    return `${weight}`
    }if(planet === 'Mars') {
    weight = earthWeight * .377
    return `${weight}`
    }if(planet === 'Jupiter') {
    weight = earthWeight * 2.36
    return `${weight}`
    }if(planet === 'Saturn') {
    weight = earthWeight * 0.916
    return `${weight}`
    } else {
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
       }
    }
    
    
    // Uncomment the line below when you're ready to try out your function
     console.log(calculateWeight(100, 'Jupiter')) 

1 Answer 1

1

Couple of changes :

First there is a difference in the way you have written multiple ifs and if, else-if. The first one will run all planet conditions even if the 1st one is satisfied. You do not want that.

Second, try to return your statement from inside the function. You are returning only weight for a planet.

With the statement in place all you need is the weight value and your job can be done with a single return statement.

function calculateWeight(earthWeight, planet) {
let weight;
if(planet === 'Mercury') {
weight = earthWeight * .378
}else if(planet === 'Venus') {
weight = earthWeight * .907
}else if(planet === 'Mars') {
weight = earthWeight * .377
}else if(planet === 'Jupiter') {
weight = earthWeight * 2.36
}else if(planet === 'Saturn') {
weight = earthWeight * 0.916
} else {
return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
   }
return `If this object were on ${planet} it would weight ${weight}.`
}


// Uncomment the line below when you're ready to try out your function
 console.log(calculateWeight(100, 'Jupiter'))

Sign up to request clarification or add additional context in comments.

1 Comment

So, because I wrote multiple if statement vs writing else if statements the code will continuously run. I understand. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.