Concatenate several numbers to get a string in JavaScript
This post will discuss how to concatenate several numbers to get a string in JavaScript.
There are several methods to concatenate several numbers to get a string in JavaScript. Here are some of the most common functions, along with some examples:
1. Using + operator
This method can be used to concatenate any number of integers to a string by using the + operator with an empty string as the first operand. This will force the type conversion of the integers to strings and perform string concatenation. For example, to concatenate 5, 6, and 7 to a string, we can use:
|
1 2 3 4 5 6 |
let num1 = 5; let num2 = 6; let num3 = 7; let result = "" + num1 + num2 + num3; console.log(result); // "567" |
We can also convert an integer to a string first using the String() constructor or toString() function, which can then be concatenated with other integers. Here’s an example:
|
1 2 3 4 5 6 7 8 9 |
let num1 = 5; let num2 = 6; let num3 = 7; let result1 = String(num1) + num2 + num3; console.log(result1); // "567" let result2 = num1.toString() + num2 + num3; console.log(result2); // "567" |
2. Using ES6 template literals
We can concatenate any number of integers to a string by using the ES6 template literals syntax, which allows embedding expressions in a string literal enclosed by backticks. For example, to concatenate 5, 6, and 7 to a string, we can use:
|
1 2 3 4 5 6 7 8 |
let num1 = 5; let num2 = 6; let num3 = 7; // Concatenate the integers using template literals let result = `${num1}${num2}${num3}`; console.log(result); // "567" |
3. Using Array.join() function
We can concatenate any number of integers to a string by creating an array of the integers and then using the Array.join() function, which returns a new string that is the result of joining all the array elements with a specified separator. For example, to concatenate 5, 6, and 7 to a string, we can use:
|
1 2 3 4 5 6 7 8 |
let num1 = 5; let num2 = 6; let num3 = 7; // Concatenate the integers using join let result = [num1, num2, num3].join(""); console.log(result); // "567" |
This function is useful when we have an array of integers or when we want to specify a different separator between the integers. That’s all about concatenating several numbers to get a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)