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 trialJason Savage
Full Stack JavaScript Techdegree Student 1,928 PointsString returned instead of Sum - Practice If and Else Statements- Solution
let num1;
let num2;
let userNum1;
let userNum2;
alert("Let's do some math!");
num1 = prompt('Please enter a number.');
if ( isNaN(num1) ) {
alert('You must enter a numeric value.');
} else {
userNum1 = parseFloat(num1);
}
num2 = prompt('Please enter another number.');
if (parseInt(num2) === 0) {
alert('You cannot divide by 0. Please try again.');
} else if ( isNaN(num2) ) {
alert('You must enter a numeric value.');
} else {
userNum2 = parseFloat(num2);
}
let message = "<h1>Math with the numbers " + num1 + " and " + num2 + "</h1>";
message += num1 + " + " + num2 + " = " + (num1 + num2);
message += "<br>";
message += num1 + " * " + num2 + " = " + (num1 * num2);
message += "<br>";
message += num1 + " / " + num2 + " = " + (num1 / num2);
message += "<br>";
message += num1 + " - " + num2 + " = " + (num1 - num2);
const message2 = "<h1>You did not enter the appropriate values, refresh and try again.</h1>";
if ( isNaN(userNum1) || isNaN(userNum2) ) {
document.write(message2);
} else {
document.write(message);
}
When printing to the page:
message += num1 + " + " + num2 + " = " + (num1 + num2);
Returns the two numbers as a string instead of the sum; however, the other equations work.
I am not sure what I did wrong.
1 Answer
Jason Savage
Full Stack JavaScript Techdegree Student 1,928 PointsI altered the line of to this:
message += `${num1} + ${num2} = ${parseInt(num1) + parseInt(num2)}`;
and it worked.