JavaScript Template Literals

Template literals (also called template strings) allow for string interpolation of expressions using a curly brackets syntax placeholder. Template literals are defined with backticks (`) and look like this:

let text = `This is a template literal`

Now if we want to see how string interpolation works, take a look at this example:

let name = 'Matt';

console.log(`My name is ${name}`);

You can apply any expression to a placeholder in the string. Such as:

console.log(`Lets add 2 + 2 ${2 + 2}`);
console.log(`2 + 2 equals ${true ? 4 : 0}`);
const add = (x, y) => x + y;
console.log(`2 + 2 equals ${add(2, 2)}`);

Tagged Templates

Template literals are mostly used for string interpolation, as demonstrated above. However, you can additionally define your own custom template parser. Take a look at this example:

function speedParser(strings, speed) {
	speedStr = speed > 100 ? 'fast' : 'slow';
	return `${strings[0]}${speedStr}`;
}

let speed = 120;
console.log(speedParser`You are driving ${speed}`);

speed = 80;
console.log(speedParser`You are driving ${speed}`);

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *