Features Of ES6 Part 7: Template Literals

Thursday, September 18, 2014

Template literals provide JavaScript with some basic string formatting capabilities. Just like many template technologies, template literals in JavaScript consist of literal text, and placeholders where the runtime can evaluate an expression to poke data into the text.

let name = "Scott";
let message = `Hello, ${name}!`;

expect(message).toBe("Hello, Scott!");

Backtick characters (`) enclose the entire template literal, while $ and {} denote the substitutions. Inside a substitution, you can use identifiers and expressions.

let showTheMath = function(x,y ){
    return `${x} + ${y} is ${x + y}`;
};

let result = showTheMath(3,4);

expect(result).toBe("3 + 4 is 7");

Template literals can even span multiple lines.

let message = `This is
               a short, but multi-line message`;

Note that message will contain a newline character because newlines (and trailing spaces) are significant inside of a template literal.

Template literals are a useful addition to the language. However, template literals become exceptionally interesting when using them with a tag. We’ll look at tagged template literals next week.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!


Comments
Thursday, September 18, 2014
Looks like the validation is broken? >:(
gravatar scott Thursday, September 18, 2014
That appears to be fine.
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!