Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 829 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



String Templates in ES6

4:12 JavaScript lesson by

ECMAscript 6 lets us use string templates to gain a lot more control over strings in JavaScript.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

ECMAscript 6 lets us use string templates to gain a lot more control over strings in JavaScript.

Avatar
Bharat

Question,
What is the current adoption status of ECMAscript 6 both on the client side (browser vendors) and server side (node or is there any other server-side Javascript technologies that are worth considering)?
Seems to me that it is ushering in revolutionary changes in how Javascript works and makes is a respectable language, e.g., Ruby.
Please provide some practical advice.
Thanks.
Bharat

In reply to egghead.io
Avatar
Sidhartha

This doesn't work in traceur and throws a ModuleEvaluationError: Object # has no method 'setProperty'

In reply to egghead.io
Avatar
Alan

Probably worth mentioning that a template handler doesn't have to return a string. It can return any JavaScript value. So you can use template handlers to implement custom DSLs to describe arbitrary structures. At ArangoDB we use a template handler for the query language to make it easier to add bound parameters to a query: https://github.com/arangodb/arangojs/blob/master/src/aql-query.js

Avatar
Gene

Not a criticism of the lesson but a comment on the code
function
tag(strings, ...values){
The
code that produces is hard to read maintain. The template syntax is great referring to variables by name. Nice and readable. But then using the tag function to manipulate the strings where positional arguments are inferred or hidden behind the runtime output leads to maintainability errors. I wonder if there is a better example of using the tag type syntax.

Avatar
Alberto Díaz

I got this error, any idea?

function tag(strings, ...values){
^^^

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module.compile (module.js:373:25)
at Object.Module.
extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3

If you have ever worked with strings in JavaScript, you've most likely concatenated two strings by just saying the variable then plus and then adding a string to it, and then when you run it, you just get Hello, World, all put together.

var salutation = "Hello";
var greeting = salutation + ", World";

console.log(greeting);

ES6 allows you to put your variables inside of your string. I'm going to surround this with a grave. So I'll put one there and I'll put one here.

Then, instead of doing plus and then quote, I'll just surround this guy with the dollar sign, curly brace, and then close curly brace. You'll see if I rerun this, I'll get Hello , World.

var greeting = `${salutation} , World`;

It actually maintained this space because I forgot to delete it. So if I delete that and run it again, then we'll get Hello, World without the space.

var greeting = `${salutation}, World`;

It actually respects white space even across multiple lines. If I put some lines in here and if I say hello, tab, tab, world, and run this. You'll see I get some blank lines, hello all the way at the left and then a couple tabs, and then world, and then more blank lines.

var greeting = `

${salutation}, 

    World


`;

String Templates Respect Whitespace

I could pull off things like hello you crazy world, how are you, and rerun this and you can see, we can manipulate strings however we'd like.

var greeting = `

${salutation}, 
  You
    Crazy       World

    How
  Are
      You  

`;

If I want to extract any of these into variables, I could just instead of World here, I could just do place and then I can do place. We'll just say planet, and rerun this, and you can see we get hello, you crazy planet, all the way out here.

var place = "planet";
var greeting = `

${salutation}, 
  You
    Crazy       ${place}

    How
  Are
      You  

`;

It's also worth noting that you can do expressions inside of these braces. If you want to do X + Y, then just show Y and just show X, and then run this. You can see we get 1 + 2 = 3, and then this is one.

var x = 1;
var y = 2;
var equation = `${ x } + ${ y } = ${x + y}`

console.log(equation); // "1 + 2 = 3"

There's this string plus, there's two, there's the string equals, and then X + Y is the expression.

Lastly, is a basic introduction to tagging these string templates that I have. It's and then the hour of the day,${new Date().getHours()}, and then, I'm sleepy. If I run this, you'll see it's 15 or 3 o'clock, and that I'm sleepy.

var message = `Its ${new Date().getHours()} Im sleepy`;

console.log(message); // "It's 15 I'm sleepy"

I don't get sleepy until after 20, so all I have here is this and how am I going to make this into a variable? Well, I can actually parse out this message and get this value and change this string based on this value.

I'm going to create a function called, tag(), and notice I don't put any sort of parameters or anything around this. I just type the function name.

var message = tag`Its ${new Date().getHours()} Im sleepy`;

I'll say, function tag, you can name it whatever you want, tag or parse, or whatever, and then it takes these strings and the ...values, these strings being an array.

function tag(strings, ...values){
  console.log(strings); // [ 'It\'s', 'I\'m sleepy' ]
  console.log(values);  // [ 15 ]
}

We'll log this out. The array of It's and I'm sleepy are the two strings. This piece and this piece, and then the values are the values found in here.

When I log this out, this will be an array with just 15 in it. So switch this over to a value. We'll just make it an empty value, ${}.

var message = tag`Its ${new Date().getHours()} Im ${""}`;

Then, we'll say, if the first value, so value 0 < 20. I'll assign the second value and say this should be I'm awake.

function tag(strings, ...values){
  if(values[0] < 20){
    values[1] = "awake";
  }
}

Then, we will turn a new string. So two back ticks, and we'll just say, return `${strings[0]}${values[0]}${strings[1]}${values[1]}`

Then, once we log this out, you can see it says, It's 15, I'm awake, because 15 is less than 20 and we assign this second value which is this guy to awake.

Now, there's much more advanced stuff you can do with this such as parsing HTML and using RegEx and everything, but we're going to end right there for right now.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?