String Concatenation (Before ES6)
Before the introduction of template literals in ES6, string concatenation was the primary method for creating strings with variables. It involves using the plus (+) operator to join strings and variables together.
For example:
JavaScript
const name = 'Rinki';
const age = 20;
const sentence = 'My name is ' + name + ' & I am ' + age + ' years old.';
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Rinki & I am 20 years old.
In this example, we define the `name` and `age` variables and then create the `sentence` string by concatenating the string literals and variables using the `+` operator. The resulting string is logged to the console.
While string concatenation works, it can become difficult to read and maintain when dealing with many variables or complex expressions. Here's an example that demonstrates this:
JavaScript
const firstName = 'Harsh';
const lastName = 'Sanjana';
const age = 19;
const city = 'Mumbai';
const sentence = 'My name is ' + firstName + ' ' + lastName + ', I am ' + age + ' years old, & I live in ' + city + '.';
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Harsh Sanjana, I am 19 years old, & I live in Mumbai.
As you can see, the string concatenation becomes harder to read and manage as more variables are added. This is where template literals provide a more readable and maintainable alternative.
String.concat() Method
The `String.concat()` method is another way to concatenate strings in JavaScript. It takes one or more strings as arguments and returns a new string that combines the original string with the provided arguments.
For example:
JavaScript
const str1 = 'Hello';
const str2 = 'World';
const result = str1.concat(' ', str2, '!');
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output
Hello World!
In this example, we have two strings, `str1` and `str2`. We use the `concat()` method on `str1` and provide the additional strings as arguments, including a space (`' '`) and an exclamation mark (`'!'`). The `concat()` method returns a new string that combines all the provided strings, which is then stored in the `result` variable and logged to the console.
You can also chain multiple `concat()` calls together to concatenate multiple strings:
JavaScript
const name = 'Sinki';
const age = 22;
const sentence = 'My name is '.concat(name).concat(' & I am ').concat(age).concat(' years old.');
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Sinki & I am 22 years old.
In this example, we use multiple `concat()` calls to build the `sentence` string by concatenating the string literals and variables. Each `concat()` call returns a new string that includes the previous string and the provided argument.
While the `String.concat()` method provides a more readable alternative to the `+` operator for string concatenation, it can still become verbose when dealing with many variables or expressions. Template literals offer a more concise and maintainable syntax for such cases.
Array Join Method
The `join()` method is an array method that creates a string by concatenating all the elements of an array, separated by a specified separator. While it is primarily used to join array elements, it can also be used for string interpolation.
For example:
JavaScript
const name = 'Ravi';
const age = 20;
const city = 'Delhi';
const sentence = ['My name is', name, '& I am', age, 'years old. I live in', city + '.'].join(' ');
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Ravi & I am 20 years old. I live in Delhi.
In this example, we create an array that contains string literals and variables. We then use the `join()` method on the array, specifying a space (`' '`) as the separator. The `join()` method concatenates all the elements of the array, using the specified separator between each element, and returns the resulting string. The final string is stored in the `sentence` variable and logged to the console.
The `join()` method can be useful when you have an array of strings or variables that you want to concatenate into a single string. However, it may not be as readable or intuitive as using template literals or other string interpolation methods.
Let’s discuss an another example that shows how to use `join()` with an array of variables:
JavaScript
const name = 'Mehak';
const age = 19;
const city = 'Pune';
const interests = ['reading', 'painting', 'traveling'];
const sentence = [
'My name is', name + '.',
'I am', age, 'years old.',
'I live in', city + '.',
'My interests are:', interests.join(', ') + '.'
].join(' ');
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Mehak. I am 19 years old. I live in Pune. My interests are: reading, painting, traveling.
In this example, we have an array of variables, including an array of interests. We create an array that contains string literals and variables, and we use the `join()` method twice: once to join the `interests` array with a comma and space separator (`', '`), and then to join the entire array of strings and variables with a space separator (`' '`). The resulting string is stored in the `sentence` variable and logged to the console.
Using a Function
Another way to achieve string interpolation is by using a function that takes variables as arguments and returns a formatted string. This approach can be useful when you need to reuse the same string interpolation logic in multiple places.
For example:
JavaScript
function createSentence(name, age, city) {
return `My name is ${name} & I am ${age} years old. I live in ${city}.`;
}
const name1 = 'Rahul';
const age1 = 21;
const city1 = 'Mumbai';
const sentence1 = createSentence(name1, age1, city1);
console.log(sentence1);
const name2 = 'Rinki';
const age2 = 20;
const city2 = 'Delhi';
const sentence2 = createSentence(name2, age2, city2);
console.log(sentence2);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Rahul & I am 21 years old. I live in Mumbai.
My name is Rinki & I am 20 years old. I live in Delhi.
In this example, we define a function called `createSentence` that takes three parameters: `name`, `age`, and `city`. Inside the function, we use template literals to create a string that interpolates the provided variables. The function returns the resulting string.
We then create two sets of variables (`name1`, `age1`, `city1` and `name2`, `age2`, `city2`) and call the `createSentence` function twice, passing in the respective variables as arguments. The returned strings are stored in the `sentence1` and `sentence2` variables and logged to the console.
Using a function for string interpolation can help keep your code DRY (Don't Repeat Yourself) by centralizing the string formatting logic. It also allows for easier maintenance and updates, as you only need to modify the function if the string format needs to change.
Let’s see an another example that shows using a function with default parameter values:
JavaScript
function createIntroduction(name, age, city, occupation = 'student') {
return `My name is ${name}, I am ${age} years old, & I live in ${city}. I am a ${occupation}.`;
}
const intro1 = createIntroduction('Harsh', 19, 'Pune');
console.log(intro1);
const intro2 = createIntroduction('Sanjana', 22, 'Bangalore', 'software engineer');
console.log(intro2);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is Harsh, I am 19 years old, & I live in Pune. I am a student.
My name is Sanjana, I am 22 years old, & I live in Bangalore. I am a software engineer.
In this example, the `createIntroduction` function takes four parameters, with the `occupation` parameter having a default value of `'student'`. If an occupation is not provided when calling the function, it will default to `'student'`. We call the function twice, once with three arguments and once with four arguments, and log the resulting strings to the console.
Tagged Template Literals
Tagged template literals provide a way to define a function that can process the parts of a template literal before they are interpolated into the final string. The function, called a tag function, receives the string literals and expressions as separate arguments, allowing you to modify or manipulate them before combining them into the final string.
For example:
JavaScript
function highlight(strings, ...values) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += `<mark>${values[i]}</mark>`;
}
}
return result;
}
const name = 'Sinki';
const age = 22;
const city = 'Hyderabad';
const sentence = highlight`My name is ${name} & I am ${age} years old. I live in ${city}.`;
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
My name is <mark>Sinki</mark> & I am <mark>22</mark> years old. I live in <mark>Hyderabad</mark>.
In this example, we define a tag function called `highlight`. The tag function takes the string literals as the first argument (`strings`) and the expressions as the rest of the arguments (`...values`). Inside the function, we iterate over the `strings` array and concatenate each string literal to the `result` string. If there is a corresponding value in the `values` array, we wrap it with `<mark>` tags and concatenate it to the `result` string.
We then create variables for `name`, `age`, and `city`, and use the `highlight` tag function with a template literal. The tag function is invoked with the string literals and expressions as arguments, and it returns the modified string with the expressions wrapped in `<mark>` tags. The resulting string is stored in the `sentence` variable and logged to the console.
Tagged template literals provide a powerful way to customize the behavior of string interpolation. You can use them to implement various functionalities like escaping HTML characters, formatting dates or numbers, or applying syntax highlighting to code snippets.
Let’s take an example that clearly shows how we can use a tagged template literal for internationalization:
JavaScript
function i18n(strings, ...values) {
const translations = {
'Hello': 'Bonjour',
'Goodbye': 'Au revoir',
'Thank you': 'Merci'
};
let result = '';
for (let i = 0; i < strings.length; i++) {
result += translations[strings[i]] || strings[i];
if (i < values.length) {
result += values[i];
}
}
return result;
}
const name = 'Ravi';
const sentence = i18n`Hello ${name}, Thank you for visiting. Goodbye!`;
console.log(sentence);

You can also try this code with Online Javascript Compiler
Run Code
Output
Bonjour Ravi, Merci for visiting. Au revoir!
In this example, the `i18n` tag function takes the string literals and expressions as arguments. It defines a `translations` object that maps English phrases to their French translations. Inside the function, it iterates over the `strings` array and replaces each string literal with its corresponding translation from the `translations` object, if available. If a translation is not found, it uses the original string literal. The expressions are interpolated into the resulting string as is.
When we use the `i18n` tag function with a template literal, it replaces the English phrases with their French translations, resulting in a localized string.
Frequently Asked Questions
Can I use string interpolation with single or double quotes instead of backticks?
No, string interpolation using ${} syntax only works with backticks (`) in JavaScript.
Is string concatenation still relevant after the introduction of template literals?
While template literals provide a more readable and convenient way to create strings with variables, string concatenation is still valid and can be used in situations where template literals may not be available or appropriate.
Can I use expressions inside the ${} syntax in template literals?
Yes, you can use any valid JavaScript expression inside the ${} syntax, including function calls, arithmetic operations, and ternary operators.
Conclusion
In this article, we explained different methods of string interpolation in JavaScript. We learned about template literals, which provide a concise and readable way to create strings with embedded expressions. We also looked at string concatenation, the String.concat() method, the array join() method, and using functions for string interpolation. Moreover, we talked about tagged template literals, which allow you to define custom functions to process and manipulate the parts of a template literal before interpolation.
You can also check out our other blogs on Code360.