Combining Strings and Numbers
+ operator as the concatenation operator (as opposed to the the addition operator). The number is first converted to a string and then concatenated (or combined) with the other string. By concatenating the two, you create one long string. Here is an example:
+ operator, it knows not to perform addition, but instead concatenation. The
var tacos = '3'; var burgers = 2; var total = tacos + burgers; //total equals '32' string value
In this example, the variable
total is equal to the string
'32'. To prevent the variable
total from becoming a string, change the last line of code to:
var total = +tacos + burgers;
*NOTE: If the operator was a
/ then a mathematical operation would have taken place instead of a concatenation.
When you put a
Another way to make sure your number is not a string is to use the
Number() command like this:
var tacos = "3"; var burgers = 2; var total = Number(tacos) + burgers;
Number() command will convert a variable that is a string to a variable that is a number (the number will not change, only the data type). If the variable is a string of characters that doesn't spell out a number, the
Number() command returns a value of
NaN (not a number). What this means is that you can't turn this particular string into a number.
You most often get numbers as strings when you get user input from a web form. In these situations, if you have to do addition, run the number through the
Number() command first.