How to do String Interpolation in JavaScript
Table of Contents
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.
JAVASCRIPTconst name = "John";
const greeting = "Hello " + name;
console.log(greeting);
BASHHello 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.
JAVASCRIPTconst name = "John";
const greeting = `Hello ${name}`;
console.log(greeting);
BASHHello 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.
JAVASCRIPTconst name = "John";
const greeting = `Hello ${name}`;
console.log(greeting);
BASHHello John
The cool thing about string interpolation with template literals is that you can use any JavaScript expression inside of the string.
JAVASCRIPTconst name = "John";
const greeting = `Hello ${name.length}`;
console.log(greeting);
BASHHello 4
This also means you can call methods from inside of the string as well:
JAVASCRIPTconst getStringLength = (string) => string.length;
const name = "John";
const greeting = `Hello ${getStringLength(name)}`;
console.log(greeting);
BASHHello 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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js