objc_bd
objc_bd

Reputation: 239

Concatenating variables which hold integers

Which is the best way to concatinate 2 variables that hold integers ?

var var1 = 1;
var var2 = 2;

console.log(var1 + var2) //result 3; expected 1 2

Upvotes: 0

Views: 74

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

Just use string concatenation explicitly by including a string literal:

console.log(var1 + " " + var2);

Or in a different situation where you didn't want the space, you could use:

console.log(var1 + "" + var2);

or perform the string conversions first explicitly, and then concatenate them:

console.log(var1.toString() + var2.toString());

Or use concat:

console.log(String.prototype.concat(var1, var2));

Upvotes: 5

Related Questions