Borislav Hadzhiev
Fri Oct 22 2021·1 min read
Photo by Stephen Leonardi
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.
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.
console.log(1 + 'hello'); // 👉️ '1hello' console.log(1 + '10'); // 👉️ '110' console.log('100' + 200); // 👉️ '100200'
string
, if you need the result as a number, pass it to the Number
object.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.
// ⛔️ Doesn't work console.log(1 + 5 + ''); // 👉️ 6 // ✅ Does work console.log('' + 1 + 5); // 👉️ 15