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

My code. I rewrote it 3 times to get it this short. From 51 lines down to 11. Can it be any shorter?

alert("Let's do some math!")
const num1=+prompt("Number #1")
const num2=+prompt("Number #2")

const message = `<h1>Basic Math with Numbers ${num1} and ${num2}</h1>
                <h2>${num1} + ${num2} = ${num1 + num2} <br>
                ${num1} - ${num2} = ${num1-num2}<br>
                ${num1} * ${num2} = ${num1*num2}<br>
                ${num1} / ${num2} = ${num1/num2}</h2>`;

document.querySelector("body").innerHTML= message

2 Answers

Steven Parker
Steven Parker
231,140 Points

Down from 51? Good job! :+1: But any shorter and it will start becoming pretty obscure and hard to read. The unary plus instead of "parseInt" is already leaning in that direction.

And for "best practice" code, always end a statement with a semicolon, even when you can get by without one.

Can unary plus replace parseInt? I didn't realize =+ also converts a string to an integer. If so, why use parseInt?

Steven Parker
Steven Parker
231,140 Points

They aren't quite the same. For examples, parseInt("12px") is 12 but +"12px" is NaN . On the other hand, parseInt("") (on an empty string) is NaN but +"" is 0.

Got it! Thank you.

Thank you Steven Parker. Yes I understand the semicolon, I will try to be more careful about that. I appreciate your feedback