devxlogo

Concatenate Variables Containing Numbers

Concatenate Variables Containing Numbers

Question:
I need to know how to concatenate variables containing numbers, that is, string them together one after the other. Every method I know simply adds the various numbers together and spits out the sum.

Answer:

You’re right?if you simply try to add the variables together using the plus (+) operator you’ll get the values added numerically. For example, given that:

var a = 5;var b = 10;var c = 999;

This code correctly displays the value 1014:

alert (a + b + c);

What you want to do is to trick the JavaScript interpreter into thinking that you want a string result, not a numeric one. An easy way to do that is to include a string constant as one of the items being added. This results in the variables being treated as strings instead of numerals. In addition, if the string you throw into the mix is an empty one it won’t disrupt what you’re trying to accomplish. For example, this code displays 510999 as you’d expect:

alert ("" + a + b + c);

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist