What are Template literals (Template strings) in JS?

October 26, 2018

Template literals are string literals which let you include some expressions. You can also use them for multi line strings. Before ES2015 they were known as Template Strings, but now they're called Template Literals.

To use them, use the backtick (probably next to your left shift key, or next to your 1 key): ....

You can use the ${variable_name} format to put values into the string:

Here is an example:

let name = "Microsoft";
let sector = "IT";
let country = "USA";
console.log(`
Hello, this is a string (multi line).
${name} is a ${sector} company, based in ${country}
`);
Hello, this is a string (multi line).

Microsoft is a IT company, based in USA

You can also put expressions like this:

console.log(`The answer to your question is: ${50+12}`); 
The answer to your question is: 62

And even things like functions:

function webdevetc_url() { return "https://webdevetc.com/"; }
console.log(`The url is ${webdevetc_url()} `); 
The url is https://webdevetc.com/