How to calculate during string interpolation?

Hello please i will like to know if this code is correct

else if (actualSleepHours > idealSleepHours) {
    console.log(`You got ${actualSleepHours} - ${idealSleepHours} hours more sleep than needed this week. Get busy and do not be lazy.`);

What i want to achieve is for this ( {actualSleepHours} - {idealSleepHours}) to print out the value of this arithmetic calculation on the console

Note: I know i can use variables for this, but i want to know if it is possible to do the calculation inside the console.log string.

Run this code and check if the result is what you expect it to be. You don’t need anybody’s help to check if your code is correct.

let actualSleepHours = 12;
let idealSleepHours = 7;

console.log(`You got ${actualSleepHours} - ${idealSleepHours} hours more sleep than needed this week. Get busy and do not be lazy.`);

will print out You got 12 - 7 hours more sleep than needed this week. Get busy and do not be lazy.. Try to figure out why - is part of the printed string and is not treated as a part of the expression.

And remember that you can always check the documentation / reference materials. Take a look at this example from the MDN -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Expression_interpolation. This should help you solve your problem.

2 Likes

This is what i have been getting thus far, but what i want to get is 5, not 12 - 7

Take a look at this example from the MDN -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Expression_interpolation. This should help you solve your problem.

1 Like

Thanks mate!! got the solution from the link you sent. I am grateful

2 Likes

This is the correct code:
else if (actualSleepHours > idealSleepHours) {
console.log(You got ${actualSleepHours - idealSleepHours} hours more sleep than needed this week. Get busy and do not be lazy.);

1 Like

You’re very welcome! Good job on fixing this one :slight_smile:

2 Likes