This can happen in less obvious circumstances, such as if you store a string entered by the user in to a variable, and then add 1 to the variable.
Since this kind of mistake can produce confusing results, it's usually preferable to use template literals instead of +
for producing strings, and stick to only using +
for mathematical addition with numbers.
Converting between strings and numbers
JavaScript often automatically converts values, such as how string + number will automatically convert number in to a string, and then append it to the first string. Sometimes you want to deliberately convert between types though. For example the user may type a number in to a text input field, which will return a string, but you want to use it as a number instead. It's also often regarded as better programming style to explicitly convert values, rather than relying on implicit language features that convert for you.
There are actually lots of ways to explicitly convert values in JavaScript, but we'll focus on just one for now: using Number()
and String()
functions. Using Number(string)
will convert a string to a number.
// Try entering in to the console:
Number("5") // 5 (number)
Number("-6.5") // -6.5 (number)
Number(5) // 5 (still a number)
Number("Hello") // NaN
Notice in the last number we got the special Not A Number (NaN) result again. This is because the string "Hello" does not represent a valid number, so we get a special result to indicate this.
Similarly, String()
can convert a number to a string.
String(5) // "5" (string)
String(-6.5) // "-6.5" (string)
String("Hello") // "Hello" (still a string)
String(NaN) // "NaN" (string)
Note that numbers can always be converted to a string. If you convert the special NaN value to a string, you get a string which says "NaN". (This conversion is successful; it's correctly turned a number value in to a corresponding string.)
Also note that in both cases, if you convert a type to the same type, like String("Hello")
, it just returns the same value unaltered. This is useful as if you're ever unsure if a value is a string or a number, you can use String(value)
, and you know the result is definitely a string.