How to do String Interpolation in JavaScript

Updated onbyAlan Morel
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.

JAVASCRIPT
const name = "John"; const greeting = "Hello " + name; console.log(greeting);
BASH
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.

JAVASCRIPT
const name = "John"; const greeting = `Hello ${name}`; console.log(greeting);
BASH
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.

JAVASCRIPT
const name = "John"; const greeting = `Hello ${name}`; console.log(greeting);
BASH
Hello John

The cool thing about string interpolation with template literals is that you can use any JavaScript expression inside of the string.

JAVASCRIPT
const name = "John"; const greeting = `Hello ${name.length}`; console.log(greeting);
BASH
Hello 4

This also means you can call methods from inside of the string as well:

JAVASCRIPT
const getStringLength = (string) => string.length; const name = "John"; const greeting = `Hello ${getStringLength(name)}`; console.log(greeting);
BASH
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.