How to Concatenate Two Numbers in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20211 min read

Concatenate Two Numbers in JavaScript #

To concatenate two numbers in javascript add an empty string to the numbers, e.g. "" + 1 + 2. When using the addition operator with a string and a number, it concatenates the values and returns the result.

index.js
const num1 = 1; const num2 = 2; const concat = '' + num1 + num2; console.log(concat); // ๐Ÿ‘‰๏ธ '12' console.log(typeof concat); // string

We used the Addition (+) operator to concat two numbers.

When used with a number and a string, the operator concatenates them.

index.js
console.log(1 + 'hello'); // ๐Ÿ‘‰๏ธ '1hello' console.log(1 + '10'); // ๐Ÿ‘‰๏ธ '110' console.log('100' + 200); // ๐Ÿ‘‰๏ธ '100200'
Note that the result has a type of string, if you need the result as a number, pass it to the Number object.
index.js
const num1 = 1; const num2 = 2; const concat = '' + num1 + num2; console.log(concat); // ๐Ÿ‘‰๏ธ 12 console.log(typeof concat); // string // ๐Ÿ‘‡๏ธ convert back to number const num = Number(concat); console.log(num); // 12 console.log(typeof num); // ๐Ÿ‘‰๏ธ number

Also note that the string must be added to the beginning when concatenating two numbers. If you add it at the end, the numbers would get added and the string would just convert the result to a string.

index.js
// โ›”๏ธ Doesn't work console.log(1 + 5 + ''); // ๐Ÿ‘‰๏ธ 6 // โœ… Does work console.log('' + 1 + 5); // ๐Ÿ‘‰๏ธ 15

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee