Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Sharing my solution

Super happy with this result! Figured I'd show my solution to share my approach to certain parts of the task.

alert('It\'s time to do some math!');

const firstNumberInput = prompt('Enter a number:');
const firstNumber = parseFloat(firstNumberInput);
const secondNumberInput = prompt('Enter another number:');
const secondNumber = parseFloat(secondNumberInput);

if (firstNumber && secondNumber) {
  const message = `
    <h1>Math with the numbers ${firstNumber} and ${secondNumber}</h1>
    ${firstNumber} + ${secondNumber} = ${firstNumber + secondNumber}<br>
    ${firstNumber} * ${secondNumber} = ${firstNumber * secondNumber}<br>
    ${firstNumber} / ${secondNumber} = ${firstNumber / secondNumber}<br>
    ${firstNumber} - ${secondNumber} = ${firstNumber - secondNumber}<br>
  `;
  document.write(message);
} else {
  alert('Please enter two valid numbers.');
}

3 Answers

Steven Parker
Steven Parker
231,141 Points

Using a template literal is a logical and effectively equivalent output method. :+1:

But combining numbers with the Boolean "and" operator (&&) is not an effective way to test for number validity. That's what the "isNaN" function is for.

To see the problem, try using 0 as one of the "valid numbers". :see_no_evil:

Oh! I think I see what the problem is there. A string input value of '0' is considered a falsy value thus returns false in the condition. Is this correct?

Steven Parker
Steven Parker
231,141 Points

Any non-empty string would be considered "truthy", including "0".

But they aren't strings at that point, they have been converted to numbers with "parseFloat". Then the "and" operator converts the terms into Boolan, and a 0 value translates to false.

Thank you for the information!