How to Concatenate Two Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

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'
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

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 // ✅ Works console.log('' + 1 + 5); // 👉️ 15

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.