Use Template Literals to Embed Expressions in Strings

Joe Previte
InstructorJoe Previte

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

In this lesson, you will learn how to embed expressions within strings using template literals.

Instructor: [0:00] The first thing we're going to do is write a function called HelloFromSpace. It will take one parameter called planet. It will return our template literal.

[0:14] When writing a template literal, instead of using quotes, we use backticks. We'll write HelloFromSpace, and then to include our parameter planet, we use the special syntax $ followed by curly brackets.

[0:31] Inside of there, you can include any valid JavaScript expression. In our case, we're just going to include planet. We'll console.log HelloFromSpace and pass in Mars. We'll run this using node. As you can see, the string returns includes our argument Mars.

[0:55] Let's take a look at one more example. We'll create another function called AddForMe, which will accept two parameters, a and b. It will return a template literal that says, "The sum of these two is -- and we use the $ sign and the curly brackets -- a+b."

[1:19] We'll console.log AddForMe and pass in 3 and 4. If we run this with node, we'll see that it prints out, "The sum of these two is 7."

[1:35] As you can see, anything we include in these curly brackets will be evaluated before the string is returned. This is the power of template literals in JavaScript.