Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use Template Literals to Embed Expressions in Strings

    Joe PreviteJoe Previte
    javascriptJavaScript

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

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss