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 trialCindy Truong
9,853 PointsWhy am I getting undefined? JavaScript Math Methods
I don't understand how I am getting undefined when I run this. It does the math correctly and shows the number, but 'undefined' is attached to num1 on the browser.
var num1 = prompt("Inuput Number: "); num1 = parseFloat(num1);
var num2 = prompt("Input 2nd number: "); num2 = parseFloat(num2);
var message = document.write("<h1>Math with the numbers " + num1 +" and " + num2 + ":</h1>"); message += num1 + " + " + num2 + " = " + (num1 + num2); document.write(message);
2 Answers
KRIS NIKOLAISEN
54,972 PointsRemove the first document.write when defining message. This is being included by your +=.
var num1 = prompt("Input Number: ");
num1 = parseFloat(num1);
var num2 = prompt("Input 2nd number: ");
num2 = parseFloat(num2);
var message = "<h1>Math with the numbers " + num1 +" and " + num2 + ":</h1>";
message += " " + num1 + " + " + num2 + " = " + (num1 + num2);
document.write(message);
Elijah Quesada
Front End Web Development Techdegree Graduate 32,965 PointsRemove the document.write on line 3 and just leave the very last document.write.
var num1 = prompt("Inuput Number: ");
num1 = parseFloat(num1);
var num2 = prompt("Input 2nd number: ");
num2 = parseFloat(num2);
var message = "<h1>Math with the numbers " + num1 +" and " + num2 + ":</h1>";
message += num1 + " + " + num2 + " = " + (num1 + num2);
document.write(message);
Cindy Truong
9,853 PointsI tried it and it worked perfectly. I should've looked at the code more closely. Thank you!
Elijah Quesada
Front End Web Development Techdegree Graduate 32,965 PointsTo better understand what was happening, try
console.log(document.write("hello"));
and see what you get in the console.