How to do String Interpolation in JavaScript

When you're writing your program, you will need to be able to generate dynamic strings.
The main way to accomplish this is to use string interpolation which allow you to slot in variables that will get replaced with values.
In this post, we'll learn how to do string interpolation in JavaScript.
String Interpolation using concatenation
The most basic form of string interpolation is to use the concatenation operator +
to combine strings.
const name = "John";
const greeting = "Hello " + name;
console.log(greeting);
Hello John
This approach is straightforward but it is not very flexible, especially when you want to use multiple variables.
String Interpolation using Template Literals
The more modern way to do string interpolation is to use template literals.
Template literals are a new way to write string literals that are more flexible because you can use variables and expressions inside of the string.
const name = "John";
const greeting = `Hello ${name}`;
console.log(greeting);
Hello John
You can define a template literal by using the backtick (`) character, then inserting variables by using the dollar sign ($) character and enclosing the variable in curly braces.
const name = "John";
const greeting = `Hello ${name}`;
console.log(greeting);
Hello John
The cool thing about string interpolation with template literals is that you can use any JavaScript expression inside of the string.
const name = "John";
const greeting = `Hello ${name.length}`;
console.log(greeting);
Hello 4
This also means you can call methods from inside of the string as well:
const getStringLength = (string) => string.length;
const name = "John";
const greeting = `Hello ${getStringLength(name)}`;
console.log(greeting);
Hello 4
Conclusion
In this post, we learned how to use string interpolation in JavaScript.
You can either use string concatenation or template literals to create dynamic strings that make use of variables and functions.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!