JavaScript Tagged Templates Masterclass

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Tagged Templates Masterclass

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

const person = 'Mike';
const age = 28;

const simple = `Person: ${person}, Age: ${age}.`;
console.log(simple); // Person: Mike, Age: 28.

const tagged = format`Person: ${person}, Age: ${age}.`;

function format(strings, ...expressions) {
console.log(strings); // [ 'Person: ', ', Age: ', '.' ]
console.log(expressions); // [ 'Mike', 28 ]

return strings[0] + expressions[0] + strings[1] + expressions[1] + strings[2];
}

console.log(tagged);

Understanding the Parameters

let x = 10, y = 20, z = 30;

const debug = (strs, ...exps) => {
console.log(strs, exps);
};

debug`${x}${y}${z}`;
// ['', '', '', ''], [10, 20, 30]

debug`${x}`;
// ['', ''], [10]

debug`${x + y + z}`;
// [ '', '' ] [ 60 ]

debug``;
// [''], []

Custom Interpolation

function interpolate(strs, ...exps) {
return strs.reduce(
(result, str, i) => {
const exp = (i < exps.length) ? exps[i] : '';
return result + str + exp.toUpperCase();
},
''
);
}

let pineapple = 'pineapple';
let capsicum = 'capsicum';

console.log(`I like ${pineapple} and ${capsicum} on pizza`);
console.log(interpolate`I like ${pineapple} and ${capsicum} on pizza`);
// I like PINEAPPLE and CAPSICUM

Domain Specific Language

// 2 ** 4 === 16
// 2 ^ 4 === 2

function calculate(strs, ...exps) {
const math = strs.reduce((acc, str, i) => {
return acc + str.replaceAll('^', '**') + (exps[i] ?? '')
}, '');

return eval(math);
}

const a = 2;
const b = 4;

console.log(calculate`${a} ^ ${b}`);
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

We've looked at the main use case of JavaScript template littles, also called template strings, which is smooth string and caption. You can actually provide your own custom function before a template string to completely customize the interpolation. And this is called a tagged template. Here we have two simple variables, one for a person pointing to mic and one for the age pointing to the number 28. We can put them in a simple string by using template littles and no surprise the output will match what we expect. We can actually put an identifier, or honestly any expression that s to a function before a template little to create what is known as a tag template. In syntax terms,

00:37

the identifier that we are using over here is called the tag function. We define it just like any other function in JavaScript, and there are two key parameters for a tag function. The first is an array of strings, which contains the string portions of the tagged template. So for our example, it'll contain the person, the age, and the full stop strings. And then the remaining parameters to attack function will contain the expressions that get passed in. And here we are consolidating all of them into a single array by using the JavaScript rest parameter as indicated by the triple dots. So for our example, it'll be an array containing the person's string and the age number,

01:15

note that the original type of the expression is preserved. So since age is just a number, we get a number. We do not get a string version of that number. Anything that we return from this function will be the result of the tagged template. As an example, we can simply concatenate the strings and the expressions the same way the built-in function would do. And if we log out the final tag result, it should match what we got in the simple version. And no surprise if we run this code, the contents of the simple and the tagged are the same final string. Let's take a deeper look at the parameters of tagged templates to get a deeper

01:48

understanding of the strings and the expressions that get passed in. As the arguments. We create three simple variables, X, Y, and Z, 10, 20, and 30 that we will be using for our expressions. And then we create a simple tag function, which we will use to debug the strings and the expressions that get passed in. Let's run our first experiment. We pass in a simple string containing three expressions X, Y, and Z. What do you think will be the strings and what do you think will be the expressions? What might surprise you that in addition to the three expressions, we will also get passed in four empty strings.

02:23

That is because we still have four empty strings that surround these three expressions. To simplify it further, if we only have a single expression, we essentially have two empty strings that surround that expression. Additionally, all expressions get evaluated before they get passed in. So if we have an expression X plus Y plus C, you will actually get past only one expression, which is the final result of this, which is 60. And of course, at this point, it should make obvious sense that if you only have an empty string, you will still get past a string. And since this string has no expressions, the expressions array is going to be empty. Let's implement

02:58

The same functionality as a built-in tempted string that works with any number of arguments. And this will give us the basic structure to easily create custom tag functions. We create this tag function called the interpolate that takes the strings and the expressions, and then we simply use string dot reduce to generate the final result. We use the strings array because as we saw, we are guaranteed at least one item in each iteration of the reduce. We will get back the currently computed result, the string that we are currently looking at, and the index for that string. As we know, we may or may not have any further expressions to look at.

03:33

So to make sure we check if I is less than the expressions length. And if it is, we have an expression and we pick it up from the expressions array. Otherwise, for the expression, we default to an empty string. Finally, for the updated result, we will have the previous result plus the current string, plus the current expression. And to kick everything off, we provide an initial seed value of an empty string. And this gives us exactly the same functionality as if we had never used this interplate function. And to demonstrate that we create two simple variables, pineapple and kasum, and generate two strings. The first one without using the tag, and then another one using this tag.

04:09

And now if you run this code, you can see that the output from both of the calls is exactly the same. The difference here is that now we have a framework to do any customization that we want to. For example, we can turn any of the past in expressions to the uppercase equivalent with a simple call to two uppercase. And now if you run this code, we get pineapple and capsicum and capitals with our custom tag function. The return value from a tax template function doesn't have to be a string. And really tagged templates open up a whole avenue for creating custom domain specific languages. As you might know, JavaScript does have a star,

04:43

star operator also called the exponent. So two to the power of four is 16. But what if you wanted to use the carrot for the same purpose? Unfortunately, the carrot operator does exist within JavaScript, and it's a bit wise xor. But let's be fancy and create our own custom D S L in which carrot has the same meaning as Star. Star. That is power. We create our own calculate tag function, which takes the strings and the expressions. And then within the strings that get passed in, we replace any existence of the karat with the star star. And this allows us to pass the final resulting string directly to JavaScript

05:17

valve function to get the evaluated numeric result. So for our simple example where we have a pointing to two and B pointing to four, if we calculate a karat P, we should get back the results 16. And indeed, that is what we see in the program output. The domain specific nature of tax templates is extremely powerful and used quite effectively in modern JavaScript ecosystems. For example, GraphQL and Lit, H T M O. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36