I'm working through Beginning Javascript but can't get past Chapter 2 finishing exercise 2. The exercise is to correct this bit of code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " theTotal);
</script>
</body>
</html>
I can get the correct total to display using alert, however when I remove the commenting it no longer works.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var intFirstNumber = parseInt(firstNumber, 10);
var intSecondNumber = parseInt(secondNumber, 10);
var theTotal = intFirstNumber + intSecondNumber;
alert(theTotal);
//document.write (intFirstNumber + " added to " + intSecondNumber + " equals " theTotal);
</script>
</body>
</html>
I can't figure out what about my document.write statement is wrong. Any hints? Additionally is there a more elegant way to achieve what I'm doing?
You need another +
between the "equals"
and theTotal
:
document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);
In this context, the +
sign means concatenate (append) whatever comes after it to whatever comes before it.
Further Reading: