Using template literals

Kim Massaro
18-07-2017

Template literals work the same as string literals, however they are great to use when you have multiline strings. In stead of needing single/double quotes around every string, you can easily combine the strings within backtips.

// String literal
const hiringDevelopers = 
    '<ul>' + 
        '<li>Front-end Developers</li>' + 
        '<li>Back-end Developers</li>' + 
        '<li>Full-stack Developers</li>' + 
    '</ul>';
// Template literal
const hiringDevelopers = `
    <ul> 
        <li>Front-end Developers</li>
        <li>Back-end Developers</li> 
        <li>Full-stack Developers</li>
    </ul>
`;

As you can see in the example above, the template literal makes your code look cleaner and manageable when you use multiple lines of strings.

Dynamic values

In template literals you can also use interpolation where you put an expression in the curly braces to create dynamic values. See the example below:

let nameDeveloper = `you`;
let companyName = `Competa`;

let joinUs = `Hi ${nameDeveloper}, want to level up your skills? Join ${companyName}`;

In stead of using the concatenation as we’re used to as:

"Hi " + nameDeveloper + ", want to level up your skills? Join " + companyName

When using interpolation in template literals, you can also use function expressions to make the templates reusable.

Give it a try, I’m sure you’ll find your code easier to read this way!

LEAVE A REPLY

you might also like