chrisminnick/javascriptaio

Chapter 3 Code Snippet Issue

Closed this issue · 1 comments

In Chapter 3 on Page 65, a code snippet for adding two numbers together is provided. In the paragraph after this code snippet, on page 66, it is explained that the previous code will request 2 numbers and provide the sum of these 2 numbers.

This is not what occurs. As the two numbers are requested using a prompt function the numbers are converted to strings, so when you input 12 and 24 for example you would expect to see 36 as the result as the content states, however what appears in the alert is 1224 as the number strings get concatenated and not added.

let firstNumber = prompt("Pick a number");
let secondNumber = prompt("Pick another number");
let sum = firstNumber + secondNumber;
alert(sum);

Thank you for writing and letting me know about this bug. Yes, you're correct, and those numbers need to be explicitly converted to numbers for this to function correctly.

let firstNumber = prompt("Pick a number");
let secondNumber = prompt("Pick another number");
let sum = Number(firstNumber) + Number(secondNumber);
alert(sum);

Thanks again!