Combining Strings and Numbers

By: Dusty Arlia
Published on August 28, 2012
Last Updated on Monday, July 06, 2015 at 12:52 PM
Total Updates: 3

When you combine a string literal and a number in JavaScript you use the + 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:

var totalItemsSelected = 3;
var message = "You have " + totalItemsSelected + " items selected.";

When the JavaScript interpreter sees the string next to the + operator, it knows not to perform addition, but instead concatenation. The + operator is treated as the concatenation operator and the strings are combined. When the JavaScript interpreter changes the number to a string automatically, it is called automatic type conversion.

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 -, *, Or / then a mathematical operation would have taken place instead of a concatenation.

When you put a + sign directly before a variable (with no space), it tells the JavaScript interpreter to try to convert the string to a number value.

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;

The 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.

Comments:

Ad:

Ad: