Javascript Upgrade: Tagged Template Literals

J

This is part of my series about upgrading my Javascript skills.

  1. Javascript, I hardly knew ya
  2. Javascript Upgrade: Day 1
  3. Javascript Upgrade: let/const
  4. Javascript Upgrade: Arrow functions
  5. Javascript Upgrade: default arguments for functions/template strings

This one is really cool and I can definitely see a lot of usage for it.  Continuing on from our template strings it turns out you can create functions to handle the parsing of them yourself.  So an example of that is if you wanted to bold every variable in a string instead of writing the literal with <strong> around each variable you could have a function handle it for you.

function boldThings(strings, ...values) {
  let str = '';
  strings.forEach((string, i) => {
    str += `${string} <strong>${values[i] || ""}</strong>`
  })
  return str
}

const first_name = "Shawn"
const current_location = "Sandy Beach"

const about_me = boldThings`Hi, my name is ${first_name} and I live in ${current_location}`
// Hi, my name is <strong>Shawn</strong> and I live in <strong>Sandy Beach</strong>

So as you see you create a function that takes in two arguments strings which holds an array of all the non-variable parts of the string literal and values which holds an array of the variable parts.  I haven’t learned about the … yet though I have seen it previously and it is called the spread operator.  I’m sure I’ll learn more about that soon so for now it’s being cargo culted.

It feels a bit weird to use the function without wrapping the string in brackets but that is how it works.  I feel I’ll get that wrong a fair bit.

As we’re up to the fifth post now and I’ve watched a fair few of the videos I wanted to recommend es6.io.  These posts are just my notes and I’m sure aren’t super useful for learning from but the videos have been excellent so far and I highly recommend them.  That isn’t an affiliate link or anything and I’m not being paid for this recommendation I am just genuinely enjoying the videos.

About the author

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By shawn

Other Things