JavaScript Variables and Operators

Text String Operators

One thing that can be confusing to beginners is that JavaScript uses + with text strings to mean something completely different from what it means with numbers. While with numbers + means add the numbers together with text + means concatenate them together. Concatenation basically means joining one text string onto the end of the first so that "my"+"book" gives "mybook" as a result. Where beginners tend to get confused is that while 3+3 gives 6, "3"+"3" gives "33".

You can also use += with text strings to directly add the variable or text on the right onto the end of the text string variable on the left.

Mixing Data Types

Additional confusion can arise when you are working with variables that are of different types. All operations require that the variables that they are operating on both be of the same type. Before JavaScript is able to perform any operations that involve two different data types, it must first convert one of the variables from one type to the other. You can’t add a number to a text string without first either converting the number to text or the text to a number.

When converting between data types we have two choices. We can allow JavaScript to do the conversion for us automatically or we can tell JavaScript which variable that we want to convert.

JavaScript will attempt to convert any text string into the number equivalent when performing subtraction, multiplication, division, and taking remainders. Your text string will actually need to contain something that JavaScript can convert to a number (i.e., a string like “10”) in order for the conversion to work.

If we use + then this could either mean that we want to convert the string to a number and add then or that we want to convert the number to a string and concatenate them. JavaScript can only perform one of these two alternatives. It always converts numbers to strings (since that will work whether the string contains a number or not).

Here are some examples.

1 "5" - 3 = 2;
2 "5" + 3 = "53"
3 2 + "7" = "27"
4 5 + 9 + "1" = "141"

Since subtraction only works with numbers 1 converts the text string into a number before doing the subtraction.

In 2 and 3 the number is converted to a text string before being concatenated (joined) to the other text string.

In 4 the leftmost addition is done first. Since these are both numbers they are actually added together and not treated as text. The result of this first addition leaves us with a similar situation to the third example and so the result of that addition is converted to text and concatenated.

To actually force JavaScript to convert a text string to a number we can use Number("3") or alternatively to force JavaScript to convert a number to a text string we can use String(5).

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow