Turning Text into Numbers

Input always arrives as text. Here is what happens when you forget that and use +:

const text = "7"; // from input: always a string
console.log(text + 1);

Output:

71

When one side of + is a string, + joins instead of adding. JavaScript turned the 1 into the text "1" and joined it to "7". There is no error and no warning. This is the most common beginner bug in JavaScript, because input is always a string and + is the first operator you reach for.

The fix is to convert the text to a number first:

const text = "7";
console.log(Number(text) + 1);
console.log(String(42) + 1);

Output:

8
421

Number(...) turns text into a number. String(...) goes the other way and turns a value into text, so String(42) + 1 joins again.

When the text is not a number

What if the text does not hold a number? JavaScript does not stop with an error. It gives you a special value instead:

const bad = Number("abc");
console.log(bad);
console.log(bad + 5);
console.log(Number.isNaN(bad));

Output:

NaN
NaN
true

NaN means "not a number". Any math with NaN also gives NaN, so one bad value can quietly spoil a whole calculation. To check for NaN, use Number.isNaN(x). It gives true when x is NaN.

You may also see parseInt. It reads the digits at the start of the text and ignores the rest. Number refuses text that is not a clean number:

console.log(parseInt("42px", 10));
console.log(Number("42px"));

Output:

42
NaN

The 10 tells parseInt to read the digits as a normal base-10 number. Use Number for input, because it shows you bad data right away instead of hiding it.

One more thing to know: -, * and / change strings to numbers by themselves, so "5" - 3 is 2. Only + joins. Do not depend on this. Convert input with Number as soon as you read it, and the problem goes away.

In the exercise, read a line of digits, join 1 to it with +, add 1 to it properly, and print its length.