JavaScript: The Recent Parts

Tagged Template Solution

Kyle Simpson

Kyle Simpson

You Don't Know JS
JavaScript: The Recent Parts

Check out a free preview of the full JavaScript: The Recent Parts course

The "Tagged Template Solution" Lesson is part of the full, JavaScript: The Recent Parts course featured in this preview video. Here's what you'd learn in this lesson:

Kyle live codes the solution to the exercise.


Transcript from the "Tagged Template Solution" Lesson

>> Kyle Simpson: All right, let's talk through the solution to this template literals exercise. We'll start here at the bottom. Let's go ahead and adjust our template literal so that it is going to use the tags, so we need to put upper in front of it. And in place of these underscores, we need to put in our interpolated expression.

So here we want name, and here we want twitter, and here we want topic.
>> Kyle Simpson: Now to define that function, what we wanna do is start with an empty string. So we'll start with this empty string, and that's what we'll end up returning. And then remember that strings, as an array, has one more element than values.

So all we need to do is loop over the string's array. So I'll say for (let i = 0; i < strings.length; i++). Now the strategy I'm going to use is, I'm going to use i as the index in the string's array, and I'll use i minus 1 as the index into the values of array, which means I don't need to add a values on the first iteration.

So, I'm going to say, if (i > 0), that's when I need to add in a values. And after I would have done that, then I will add in the strings[i]. So if we're on the second iteration, then we already have strings of 0 and now we wanna put in values of 0, which would be values of i minus 1.

We don't wanna just include values of i minus 1, though. We want to uppercase it, and so we would say ret += values[i-1]. And we wanna call toUpperCase on it. But there's one last little nuance, which is the values that come in don't have to be strings. In this example they are, but they could have been non-strings like numbers, in which case you would have thrown an exception.

So just to be extra safe, let's go ahead and force that the value has to be treated as a string even if it isn't a string.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now