Converting Between Text and Numbers
Introduction
Welcome back to Comparing and Converting JavaScript Values! In the previous lesson, we used typeof to tell a number from a string. That distinction becomes especially useful when a program receives text that happens to contain digits.
In this lesson, we will watch the + operator join text instead of adding numbers, then learn Number() and String() as deliberate conversions. By the end, we will be able to repair a total that is wrong because one quantity arrived as text.
The Plus Sign Has Two Jobs
We have used + for arithmetic, such as adding two numbers. JavaScript also uses + to join strings. When one side is a string, JavaScript treats the operation as joining text. Here, the string "2" is joined with the number 2:
The displayed 22 looks numeric, but the second line confirms that the joined result is a string:
This is a common surprise when values come from a form or another source that provides text. JavaScript joined the two pieces instead of calculating a sum. We can also check typeof quantityFromForm to confirm that the original value is text.
Convert Text with Number()
When text contains digits that we want to calculate with, we can place it inside Number() to convert it into a number. The parentheses hold the value we want to convert:
Now both sides of + are numbers, so JavaScript adds them. The next line confirms that the converted value is a number:
Number() gives us a new value in the number type; it does not change the original string stored under quantityFromForm. We chose the new variable name quantity to make that converted value easy to recognize.
In these examples, the text already contains digits for a quantity. Conversion and calculation are separate steps: Number() changes the type of the value we store, then + works with that number. Keeping the steps on different lines makes the program easier to follow, because we can identify whether a surprise came from the input value, the conversion, or the later calculation.
