How To Concatenate Two Numbers In JavaScript

How to Concatenate Two Numbers in JavaScript

Suppose you worry about how to concatenate two numbers in JavaScript. This article will show you many methods like using the toString() and concat() methods and converting the number to a string. Start reading the detailed article.

Let’s learn how to concatenate two numbers in JavaScript

Using the toString() method

In the first solution, we prefer using toString() to turn the firstNumber into a string and concatenate them, then return it into a new string, be two numbers concatenated. That seems to work pretty well. We have a code example below. Let’s learn with us.

Code example:

var firstNumber = 20;
var secondNumber = 22;

// Using the toString() method
const concatenate = firstNumber.toString() + secondNumber;

console.log("My first number is: ", firstNumber);
console.log("My second number is: ", secondNumber);
console.log("After concatenating two numbers: ", concatenate);

Output

My first number is: 20
My second number is: 22
After concatenating two numbers: 2022

Using the concat() method

The second way is converting the firstNumber into a string. Then, using concat() method to add a string and number into a new string. The concat() method is very useful and helps the developer in many things. We already have the article to introduce this method here. Please read it to get more information.

Example:

var firstNumber = 20;
var secondNumber = 22;

// Convert number to string using the concat() method
const concatenate = String(firstNumber).concat(secondNumber);

console.log("My first number is: ", firstNumber);
console.log("My second number is: ", secondNumber);
console.log("After concatenating two numbers: ", concatenate);

Output

My first number is: 20
My second number is: 22
After concatenating two numbers: 2022

Converting the number to a string

The last way is to use the  ” ” + firstNumber + secondNumber; to force it to strings. This is the best way, and is very easy to concatenate two numbers in JavaScript.

Example:

var firstNumber = 20;
var secondNumber = 22;

// Convert the number to a string and add two string
const concatenate = "" + firstNumber + secondNumber;

console.log("My first number is: ", firstNumber);
console.log("My second number is: ", secondNumber);
console.log("After concatenating two numbers: ", concatenate);

Output

My first number is: 20
My second number is: 22
After concatenating two numbers: 2022

Summary

Hopefully, the article about how to concatenate two numbers in JavaScript is helpful for you. Don’t hesitate to leave your comment here if you have any questions or concerns about all methods we explain in this article. Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *