Use Template Literals to Embed Expressions in Strings

Joe Previte
InstructorJoe Previte
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 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.

egghead
egghead
~ 34 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today